Stylianos Gakis
08/22/2021, 4:06 PMcoroutineScope
inside a flow operator? I have a flow I’m mapping on, and I want, depending on the value do some multiple suspending calls that I would optimally prefer to be done in parallel. Specific example inside the thread 🧵class AnimalsScreenViewModel(
private val someRepository: SomeRepository,
@DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher,
) : ViewModel() {
private val _animalType: MutableStateFlow<AnimalType> = MutableStateFlow(<http://AnimalType.Cat|AnimalType.Cat>)
val animalType: StateFlow<AnimalType>
get() = _animalType.asStateFlow()
val animalListStateFlow: StateFlow<List<Animal>> = animalType
.map { animalType: AnimalType ->
coroutineScope {
val getAnimalAsyncCalls: List<Deferred<List<Animal>>> = List(4) { index ->
async {
someRepository.getAnimals(
animalType = animalType,
page = (index + 1)
)
}
}
val animalList: List<Animal> = getAnimalAsyncCalls
.awaitAll()
.flatten()
animalList
}
}
.stateIn(
scope = viewModelScope + defaultDispatcher, // Not sure about setting a dispatcher here
started = SharingStarted.WhileSubscribed(5000),
initialValue = listOf()
)
fun setAnimalType(animalType: AnimalType) {
_animalType.value = animalType
}
}
I want to bring the emphasis on the map flow operator here
.map { animalType: AnimalType ->
coroutineScope {
val getAnimalAsyncCalls: List<Deferred<List<Animal>>> = List(4) { index ->
async {
petFinderRepository.getAnimals(
animalType = animalType,
page = (index + 1)
)
}
}
val animalList: List<Animal> = getAnimalAsyncCalls
.awaitAll()
.flatten()
animalList
}
}
I am 100% not sure about if this would work alright, and follow structured concurrency and cancel itself if the animalType
flow emits a different value in the meantime. I would love it if someone could take a peek at this and point out if there’s something obviously bad that I should be aware of, thank you.Dominaezzz
08/22/2021, 5:05 PMStylianos Gakis
08/22/2021, 5:11 PMcoroutineScope
function that’s why I just thought I’d share it here to see if there’s something obviously wrong about it, I just recently read about it on Bill Phillips’ blog here https://www.billjings.net/posts/title/foot-marksmanship-with-runblocking/ and it just so happened that I had a case where I needed access to async while I was in a simple suspend function.
But when you say depends on the operation, what comes first to your mind where it would be problematic?Dominaezzz
08/22/2021, 5:29 PMtransform
is one of them.Stylianos Gakis
08/22/2021, 5:33 PMcoroutineScope
I guess?) this would break somehow? Is that documented somewhere, I haven’t seen it mentioned before.Nick Allen
08/24/2021, 2:29 AMStylianos Gakis
08/24/2021, 7:58 PM