Hi, I can't find how to remove a subscriber to a S...
# coroutines
j
Hi, I can't find how to remove a subscriber to a StateFlow since collect never terminates. I just want to stop listening once a certain state is emitted. Thanks
Copy code
scope.launch { stateFlow.collect { if (it is State) doWork(); /* how do i unsubscribe here? */ } }
j
This should do:
Copy code
scope.launch {
    stateFlow.takeWhile { it is State }.collect { doWork() }
}
j
okay I thought I tried that and transformWhile but i'll double check. I might have been blocking something and it never completed.
i'll get back to you thanks!
n
You may also be looking for something like:
Copy code
scope.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."
j
Ah yeah I sort of assumed an else there, but technically you're right @Nick Allen
j
I'm looking to listen until a state is emitted and then stop listening
so any number of emissions can be ignored until the correct state is emitted
so the takeWhile is what i was expecting but it never completed in my sample
j
Then I don't believe
takeWhile
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:
Copy code
scope.launch {
    val item = stateFlow.filterIsInstance<State>().first()
    doWork()
}
j
ok i'll give it a whorl! thanks
that worked thank you!