是否可以在Kotlin中为mutableStateOf()提供自定义setter

q3qa4bjr  于 2022-11-25  发布在  Kotlin
关注(0)|答案(2)|浏览(177)

我想在每次设置某个状态后的两秒钟内执行一些操作。

  • viewModel内的代码:*
var isLoading = mutableStateOf(LoadingState.NONE)
    set(value) {
        Timber.d("Custom Setter") //Not Firing

        //Do something when the state is set to success.
        if(value.value == LoadingState.SUCCESS){
            viewModelScope.launch {
                delay(2000L)
                dispatchEvent(//some event)
            }
        }
        field = value
    }

set{}块根本没有运行。但值设置正确。
使用带有by关键字的委托时,
Delegated property cannot have accessors with non-default implementations
有没有办法让自定义setter在Jetpack Compose中为mutableStateOf()工作?

kiayqfof

kiayqfof1#

我认为你可以用snapshotFlow来实现这个用例。它可以从一个给定的compose State创建一个Flow

var isLoading by mutableStateOf(LoadingState.NONE)
    private set

init {
    viewModelScope.launch {
        snapshotFlow { isLoading }
            .collect { 
                if(it == LoadingState.SUCCESS) {
                    delay(2000L)
                    dispatchEvent(//some event)
                }
            }
    }
}
rqenqsqc

rqenqsqc2#

基于@ArpitShukla的答案。我们也可以使用作用域函数来封装代码块。

var isLoading by mutableStateOf(LoadingState.NONE).also{ state ->
        viewModelScope.launch {
            snapshotFlow { state.value }
                .collect {
                    if(it == LoadingState.SUCCESS) {
                        delay(2000L)
                        dispatchEvent(//Fire event)
                    }
                }
        }
    }

相关问题