Justin Tullgren
01/25/2022, 7:52 PMscope.launch { stateFlow.collect { if (it is State) doWork(); /* how do i unsubscribe here? */ } }
Joffrey
01/25/2022, 7:54 PMscope.launch {
stateFlow.takeWhile { it is State }.collect { doWork() }
}
Justin Tullgren
01/25/2022, 7:56 PMJustin Tullgren
01/25/2022, 7:56 PMNick Allen
01/25/2022, 8:13 PMscope.launch {
val item = stateFlow.first() //wait for first item
if (item is State) {
doWork()
}
}
Not really sure if the code snippet you wrote is exactly what you meant. I read that as "check the first item if work should be done and then stop listening regardless of what it is."Joffrey
01/25/2022, 8:14 PMJustin Tullgren
01/25/2022, 8:14 PMJustin Tullgren
01/25/2022, 8:15 PMJustin Tullgren
01/25/2022, 8:15 PMJoffrey
01/25/2022, 8:18 PMtakeWhile
is what you want here. If you want to subscribe and wait for the first item that is a State
you should use val state = stateFlow.first { it is State }
. Or if you want to avoid casting to State
you could use:
scope.launch {
val item = stateFlow.filterIsInstance<State>().first()
doWork()
}
Justin Tullgren
01/25/2022, 8:19 PMJustin Tullgren
01/25/2022, 8:29 PM