https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Lilly

09/21/2023, 11:44 AM
Is there a coroutine function like
singleOrNull()/firstOrNull()
that does not suspend until first item is emitted? My use case:
Copy code
suspend fun execute(dispatcher: Coroutines.Dispatcher) {
    withContext(dispatcher) {
        // do something that returns result
        // also process outstanding tasks from SharedFlow<() -> Unit>
        outStandingTask.state.singleOrNull()?.invoke() // suspends, so no result is returned
        return result
    }
}
Would a simple Queue fit better?
m

mkrussel

09/21/2023, 11:48 AM
What type is
outstandingTask.state
?
l

Lilly

09/21/2023, 11:49 AM
It's a
SharedFlow<() -> Unit>
m

mkrussel

09/21/2023, 11:55 AM
Only thing I can think of is add a timeout and then do firstOrNull and handle the timeout. If no one is trying to suspend when getting data from the
state
, then a queue might be a better fit. Polling a flow is uncommon. If you are polling multiple flows, then using channels and a select call might be better.
👍 1
l

Lilly

09/21/2023, 11:56 AM
Thanks that already helps. I know what I have to do now
2 Views