简体   繁体   English

在 Kotlin StateFlow 中使用发射

[英]Using emit with Kotlin StateFlow

Until now I was using Flow and mapping it to LiveData like below -到目前为止,我一直在使用Flow并将其映射到LiveData如下所示 -

The MyService looks like this - MyService看起来像这样 -

override fun provideData(action: MyAction) = flow {
   emit(MyResult.Loading)
   emit(dataRepository.getNewData())
}

The ViewModel looks like this - ViewModel看起来像这样 -

fun getData() = myService.provideData(MyAction.GetData).map {
                
}.asLiveData(Dispatchers.Default + viewModelScope.coroutineContext)

I want to move to StateFlow .我想转移到StateFlow How can I use emit function with StateFlow like I used it with Flow .我如何像在Flow使用它一样在StateFlow使用emit功能。

You can write your flow as before, but replace .asLiveData(scope) with .stateIn(scope, SharingStarted.Eagerly, null) to get an instance of StateFlow running in the corresponding scope with a similar behavior that you were getting with LiveData before — sharing is started immediately and the initial value is null (just like with LiveData ).您可以像以前一样编写流程,但将.asLiveData(scope)替换为.stateIn(scope, SharingStarted.Eagerly, null)以获得在相应范围内运行的StateFlow实例,其行为与您之前使用LiveData获得的行为类似 -共享立即开始,初始值为null (就像LiveData )。

You can read here for more details and explanation of all stateIn operator parameters here https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/state-in.html您可以在此处阅读有关所有stateIn运算符参数的更多详细信息和说明https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/state-in.html

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

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