'Implementing CoroutineScope in ViewModel
Why and when do we actually need to implement CoroutineScope in a ViewModel. Inside ViewModel you can use viewModelScope when you want to tied your Coroutine to the ViewModel thus when onCleared gets called all running coroutines will be cancelled automatically. When you implement CoroutineScope you can directly call launch, what scope does it use? I am guessing it uses the one provided at override val coroutineContext: CoroutineContext. Does implementing CoroutineScope in a ViewModel means you want to handle the cancellation of coroutine by yourself?
Solution 1:[1]
We can launch multiple coroutine within viewmodelscope.launch{} without coroutineScope.But Sometimes we may need values from all running coroutine to create new result.if it returns a value we can use async{}.await() but if it returns a job we can't expect updated result .
So if we launch our all coroutines within our child coroutine using coroutineScope{} ,parent coroutine will wait for child coroutine to finish it's executions before return the result.
viemodelScope.launch{val count= getCountValue() }//parent coroutine
suspend fun getCountValue(): Int {
var count = 0
lateinit var asyncDeferredResult: Deferred<Int>
//child coroutine
coroutineScope {
//returns job
launch(Dispatchers.IO) {
delay(1000)
count = 10
}
//launching another coroutine using async coroutine builder within child coroutine
asyncDeferredResult = CoroutineScope(Dispatchers.IO).async {
delay(3000)
return@async 50
}
} //child coroutine scope end
//here the parent coroutine guaranties ,the completion of all task within child coroutine scope before return the value .
// we will get expected result (10+50=60)
//if you launch more than one coroutine without child coroutinescope,sometimes you will get 0+50=50 at the end
return count + asyncDeferredResult.await()}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | androidLearner |
