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
Marc Knaup
01/26/2021, 11:26 PM
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.