简体   繁体   English

如何从另一个 class 收集 StateFlow 状态?

[英]How to collect StateFlow states from another class?

I have view model like this:我有这样的视图 model:

class SimpleViewModel : ViewModel() {
    private val _state = MutableStateFlow(false)
    val state: StateFlow<Boolean> = _state
}

How can I collect this state's values and call methods from another class like this:我如何收集此状态的值并从另一个 class 调用方法,如下所示:

class AnotherClass {
    fun doWhenViewModelStateUpdateToTrue()
    fun doWhenViewModelStateUpdateToFalse()
}

Your other class needs a reference to the state flow and to a CoroutineScope to run the collection in.您的其他 class 需要引用 state 流和 CoroutineScope 以在其中运行集合。

The CoroutineScope should have a lifecycle matching that of this class. So if it's a class you create in an Activity, for example, you would pass lifecycleScope . CoroutineScope 应该有一个与这个 class 相匹配的生命周期。因此,如果它是一个 class,你在一个 Activity 中创建,例如,你将传递lifecycleScope

class AnotherClass(
    private val coroutineScope: CoroutineScope,
    private val flowToCollect: Flow<Boolean>
) {
    init {
        coroutineScope.launch {
            flowToCollect.collect {
                if (it) doWhenViewModelStateUpdateToTrue() 
                else doWhenViewModelStateUpdateToFalse()
            }
        }
    }

    fun doWhenViewModelStateUpdateToTrue() {
        //...
    }

    fun doWhenViewModelStateUpdateToFalse() {
        //...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM