[英]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.