Stylianos Gakis
12/17/2021, 11:52 AM.collectLatest { //here }
I am not under a coroutine scope, but simply a suspend function, therefore I do not have access to CoroutineScope.async
. I should be able to do this somehow right?
ps. I’m using collectLatest with the idea that if a new value comes, the two async calls I am doing should cancel themselves since I will not be needing their result anymore, is this a correct assumption?wasyl
12/17/2021, 12:03 PMthe two async calls I am doing should cancel themselves since I will not be needing their result anymore, is this a correct assumption?yes I think for your use case you can just do
collectLatest { coroutineScope { /* asyncCalls } }
wasyl
12/17/2021, 12:03 PMStylianos Gakis
12/17/2021, 12:05 PMcoroutineScope
which gives me a CoroutineScope
receiver:
someFlow.collectLatest { collectionResult ->
coroutineScope {
val one = async { someSuspendingApiCall() }
val two = async { someOtherSuspendingApiCall() }
doSomethingWithBothResults(one.await(), two.await())
}
}
Since I am launching this entire thing inside a ViewModel (doing Android, yes) I am assuming the coroutineScope
call inherits all the outer context, aka when the viewModelScope
gets cancelled it should propagate all the way to the two async calls too?
Anything wrong with my logic? Feels a bit tricky, not sure I am thinking about it correctly.Stylianos Gakis
12/17/2021, 12:06 PMwasyl
12/17/2021, 12:12 PMcoroutineScope
creates a new scope, but it maintains structured concurrency. So if collectLatest
is cancelled, then coroutineScope
is cancelled too (and all the inner coroutines too), I think that’s even explained in the kdoc of the method with the exampleStylianos Gakis
12/17/2021, 12:14 PM