Hi :wave: I have a question regarding multiple co...
# coroutines
l
Hi 👋 I have a question regarding multiple collectors for Flow : how do you properly implement it? I tried to transform a Flow to a SharedFlow, to be able to do so. But it's no working, only the first collector called is doing his job:
Copy code
//Inside UseCase
suspend fun state(): SharedFlow<HomeState> = locationInteractor
    .canGetLocations
    .flatMapLatest { ... }
    .flowOn(ioDispatcher)
    .shareIn(
        scope = CoroutineScope(Job() + ioDispatcher),
        started = SharingStarted.Eagerly,
        replay = 1,
    )

//Inside ViewModel
suspend fun success(): Flow<List<HikeCard>> = homeInteractor
    .state()
    .filterIsInstance<HomeInteractor.HomeState.Success>()
    .map { ... }

suspend fun error(): Flow<ErrorMessages> = homeInteractor
    .state()
    .filterIsInstance<HomeInteractor.HomeState.Error>()
    .map { ... }

//Inside View
outputs.success().collect { ... }  // the only one collected because of order
outputs.error().collect { ... } // never collected, except if moved above previous collector
Am I missing / misunderstanding something? Thanks for your help!
m
collect { … }
suspends the coroutine until the Flow is complete. So the first one won’t stop collecting in your case and code that comes after it won’t be executed. You need to start collection in parallel by using multiple coroutines.
Copy code
launch {
    outputs.success().collect { ... }
}
launch {
    outputs.error().collect { ... }
}
l
That makes sense 👍 Also, I don't need to go through SharedFlow. It works simply with Flow in parallel coroutines
Thanks!
c
You probably do need a SharedFlow, even when launched in two different coroutines. Collecting
state()
twice is probably running the whole pipeline twice, not running it once with parallel collectors
👍 1
☝️ 1