【问题标题】:Jetpack Compose - Click of button doesn't work each timeJetpack Compose - 每次点击按钮都不起作用
【发布时间】:2022-11-23 17:20:38
【问题描述】:

我开发了一个小型喷气背包组合项目。单击按钮时我遇到了问题。

此外,我为这个项目使用了一些基类/函数设计。项目使用BaseViewModel类和BaseComposableScreen可组合函数来概括视图和视图模型的基本通信。

这是基本的东西:

@Composable
fun <State, Event> BaseComposableScreen(
    navController: NavController,
    viewModel: BaseViewModel<State, Event>,
    content: @Composable (coroutineScope: CoroutineScope) -> Unit,
) {
    val coroutineScope = rememberCoroutineScope()

    LaunchedEffect(Unit) {
        viewModel.effect.collect { effect ->
            when (effect) {
                is BasicEffect.NavigateToEffect -> {
                    coroutineScope.launch {
                        navController.navigate(effect.route)
                    }
                }
                is BasicEffect.NavigateBackToEffect -> {
                    coroutineScope.launch {
                        navController.popBackStack(effect.destination, effect.inclusive)
                    }
                }
                is BasicEffect.NavigateBackEffect -> {
                    coroutineScope.launch {
                        navController.popBackStack()
                    }
                }
            }
        }
    }

    content(coroutineScope)
}
abstract class BaseViewModel<State, Event> : ViewModel() {

    private val mutex = Mutex()
    private val exceptionHandler = CoroutineExceptionHandler(::onError)

    abstract fun provideInitialState(): State

    private val _state = MutableStateFlow(provideInitialState())
    val state: StateFlow<State> = _state.asStateFlow()

    private val _effect = Channel<BaseEffect>(Channel.BUFFERED)
    val effect: Flow<BaseEffect> = _effect.receiveAsFlow()

    //optional override
    open fun onEvent(event: Event) {}

    open fun onError(context: CoroutineContext, throwable: Throwable) {

    }

    protected fun emitState(state: State) {
        launchOnMain {
            mutex.withLock {
                _state.emit(state)
            }
        }
    }

    protected fun emitEffect(effect: BaseEffect) {
        launchOnMain {
            _effect.send(effect)
        }
    }

    protected fun <P, R, U : BaseUseCase<P, R>> executeUseCase(
        useCase: U,
        param: P,
        onComplete: ((R) -> Unit)? = null,
    ) {
        launchOnMain {
            val result = useCase.start(param)
            onComplete?.invoke(result)
        }
    }

    protected fun launchOnMain(block: suspend CoroutineScope.() -> Unit): Job {
        return viewModelScope.launch(exceptionHandler, block = block)
    }

    protected fun launchOnIO(block: suspend CoroutineScope.() -> Unit): Job {
        return viewModelScope.launch(exceptionHandler + Dispatchers.IO, block = block)
    }

    protected fun launchOnDefault(block: suspend CoroutineScope.() -> Unit): Job {
        return viewModelScope.launch(exceptionHandler + Dispatchers.Default, block = block)
    }

    protected fun <T> Flow<T>.launchFlow(scope: CoroutineScope = viewModelScope): Job =
        this.catch {
            exceptionHandler.handleException(currentCoroutineContext(), it)
        }.launchIn(scope)

}
abstract class BaseEffect

sealed class BasicEffect: BaseEffect() {

    data class NavigateToEffect(val route: String) : BaseEffect()

    data class NavigateBackToEffect(
        val destination: String,
        val inclusive: Boolean = false,
    ) : BaseEffect()

    object NavigateBackEffect : BaseEffect()

}

我已经为可组合屏幕及其视图模型实现了这些基本结构。他们来了:

class ChurchViewModel : BaseViewModel<Unit, ChurchEvent>() {

    override fun provideInitialState() = Unit

    override fun onEvent(event: ChurchEvent) {
        when (event) {
            is ChurchEvent.PrayToGod -> {
                emitEffect(ChurchEffect.GodListen)
            }
        }
    }

}

sealed class ChurchEffect : BaseEffect() {
    object GodListen : ChurchEffect()
}

sealed class ChurchEvent {
    object PrayToGod : ChurchEvent()
}
@Composable
fun ChurchScreen(navController: NavController) {
    val viewModel = viewModel<ChurchViewModel>()
    val scaffoldState = rememberScaffoldState()

    LaunchedEffect(Unit) {
        viewModel.effect.collect { effect ->
            when (effect) {
                ChurchEffect.GodListen -> {
                    scaffoldState.snackbarHostState.showSnackbar("God listens..")
                }
            }
        }
    }

    BaseComposableScreen(navController = navController, viewModel = viewModel) {
        ChurchScreenContent(
            scaffoldState = scaffoldState,
            onPrayToGod = {
                viewModel.onEvent(ChurchEvent.PrayToGod)
            }
        )
    }
}

@Composable
private fun ChurchScreenContent(
    scaffoldState: ScaffoldState = rememberScaffoldState(),
    onPrayToGod: () -> Unit = { },
) {
    Scaffold(scaffoldState = scaffoldState) { paddingValues ->
        Column(
            modifier = Modifier
                .padding(paddingValues)
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.SpaceEvenly,
        ) {
            Text(text = "Church")
            Icon(
                painter = painterResource(id = R.drawable.ic_baseline_location_city_24),
                contentDescription = "Church image",
                modifier = Modifier.size(90.dp),
            )
            Button(onClick = onPrayToGod) {
                Text(text = "Pray to God")
            }
        }
    }
}

问题是当我点击“向上帝祈祷”按钮时。它调用的代码只能在奇数次运行。例如,第一次点击有效,第二次无效。第三次点击有效,第四次无效。

我不知道具体原因,请帮我澄清一下这种情况!

【问题讨论】:

    标签: android kotlin mvvm android-jetpack-compose kotlin-coroutines


    【解决方案1】:

    在我看来,您需要在可组合范围内创建协程以显示小吃店。您当前的范围可能太忙,无法在每次调用时显示小吃栏。 该方法将保证您显示小吃店的范围不会被阻止。

    @Composable
    fun ChurchScreen(navController: NavController) {
        val viewModel = viewModel<ChurchViewModel>()
        val scaffoldState = rememberScaffoldState()
        val coroutineScope = rememberCoroutineScope() // Here is your scope for showing snackbar
    
        LaunchedEffect(Unit) {
            viewModel.effect.collect { effect ->
                when (effect) {
                    ChurchEffect.GodListen -> {
                        coroutineScope.launch { 
                            scaffoldState.snackbarHostState.showSnackbar("God listens..") 
                        }
                    }
                }
            }
        }
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 2022-07-29
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多