I am developing an Android application, using the MVVM design pattern.
So, I have a repository that exposes a flow<T> to a ViewModel. The ViewModel then converts the flow<T> to LiveData<T> using asLiveData() as per the code below.
repository.getFlow().map {
// I will do some long running work here
}.asLiveData()
As you can see, I will do some long-running work in map { }. So I want to execute the code inside map { } in Dispatchers.Default thread.
From my research, I can do with flowOn(Dispatchers.Default) or asLiveData(viewmodelScope.coroutineContext + Dispatchers.Default) as per the code below.
- map{} with
flowOn(Dispatchers.Default)
repository.getFlow().map {
// I will do some long running work here
}.flowOn(Dispatchers.Default).asLiveData()
- map{} with
asLiveData(viewmodelScope.coroutineContext + Dispatchers.Default)
repository.getFlow().map {
// I will do some long running work here
}.asLiveData(viewmodelScope.coroutineContext + Dispatchers.Default)
I'd like to understand better about coroutine context, scope and flowOn(). So my questions are as follows
1-1. Does asLiveData(viewmodelScope.coroutineContext + Dispatchers.Default) mean that asLiveData() function will execute in a new coroutine with Dispatchers.Default in viewmodelScope?
1-2. So, then the map {} function executes in the new coroutine with Dispatchers.Default because flow's intermediate operator executes in consumer's coroutine?
- I also read
flowOn(Dispatchers.Default)executes the upstream flow in the CoroutineContext defined inflowOn()function, which mean that the map{} will execute inDispatchers.Defaultthread. Is it fine to use flowOn() in viewmodel withasLiveData()?
Thank you guys