Reputation: 737
Until now I was using Flow
and mapping it to LiveData
like below -
The MyService
looks like this -
override fun provideData(action: MyAction) = flow {
emit(MyResult.Loading)
emit(dataRepository.getNewData())
}
The ViewModel
looks like this -
fun getData() = myService.provideData(MyAction.GetData).map {
}.asLiveData(Dispatchers.Default + viewModelScope.coroutineContext)
I want to move to StateFlow
. How can I use emit
function with StateFlow
like I used it with Flow
.
Upvotes: 1
Views: 2190
Reputation: 28658
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
).
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
Upvotes: 6