Noel Stieglitz
03/31/2021, 7:28 PMsuspend 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?Zach Klippenstein (he/him) [MOD]
03/31/2021, 7:32 PMfetchTwoThings or getStuffN from your repository isn’t really a coroutines question, it depends more on what responsibilities are appropriate for your different architectural layers.Noel Stieglitz
03/31/2021, 8:02 PMgetStuffN rather than fetchTwoThings is if there were some advantage specific to the coroutines. For instance if using the viewModelScope rather than using the coroutineScope builder were better, and it were not a good idea to pass viewModelScope down to the repository.Zach Klippenstein (he/him) [MOD]
03/31/2021, 8:06 PMNoel Stieglitz
03/31/2021, 8:06 PMursus
03/31/2021, 9:10 PMNoel Stieglitz
03/31/2021, 11:05 PMgetStuff1 and getStuff2 can run concurrentlyZach Klippenstein (he/him) [MOD]
03/31/2021, 11:21 PMgetStuff1 and getStuff2 as suspend funs, then in fetchTwoThings call them as async { getStuff1() } etc.