Hi Everyone! I have a question that straddles the Android/coroutine slack channels, but I think the heart of the question is about structured concurrency. I'm working on an Android app that has a ViewModel that references a repository. The repository exposes a method that makes two concurrent API calls and returns the result of both after both have finished. What I have now is something like this:
suspend fun fetchTwoThings(): TheResultsModel =
coroutineScope {
val job1 = getStuff1(this) // both of these functions use the passed in coroutine scope like scope.async(<http://Dispatchers.IO|Dispatchers.IO>) { ... API call here }
val job2 = getStuff2(this)
awaitAll(job1, job2)
return@coroutineScope TheResultsModel(
thing1 = job1.await(),
thing2 = job2.await()
}
Is there any downside to using the
coroutineScope
like this in the repository? Alternatively, I could pass in the
viewModelScope
. Maybe that's ok since the ViewModel class instantiates the repo as a member variable. The lifetime of the repository is already tied to the ViewModel class. Yet another option is to expose
getStuff1
and
getStuff2
to the ViewModel, and manage the coroutine there. I'm not a huge fan of that since I might want to call
fetchTwoOtherThings
from other places and would have to duplicate that code. What are your thoughts? How can I do this better?