https://kotlinlang.org logo
#flow
Title
# flow
s

Stylianos Gakis

12/17/2021, 11:52 AM
I am collecting a flow, and inside the scope of that collect function I would like to perform 2 network requests in parallel that can start independently, and simply want the result of both in the end. Inside the scope of
.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?
w

wasyl

12/17/2021, 12:03 PM
the 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 } }
I’m not 100% sure how it’ll behave with cancellation so you should test it, but overall I think it’s what you need
s

Stylianos Gakis

12/17/2021, 12:05 PM
Ah, looking around a bit, I’ve found I can wrap it all inside a
coroutineScope
which gives me a
CoroutineScope
receiver:
Copy code
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.
Aaaaand you beat me to it. That’s good, if you had the same idea, it probably means I’m on the right path. Thanks a lot! If anyone is like more certain about the cancellation I’d love to hear it. With this kind of stuff I always find it a bit hard to setup, I’d need a blank project, create my own scopes, cancel them etc. I’m probably saying all this because I’m still not super comfortable around these concepts and I am missing something, but at least it feels that way.
w

wasyl

12/17/2021, 12:12 PM
coroutineScope
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 example
s

Stylianos Gakis

12/17/2021, 12:14 PM
Yeap, you are right. It all seems to checkout, thanks again!
2 Views