LN-12
LN-12

Reputation: 1039

Suspending a Kotlin coroutine until a flow has a specific value

I am currently playing around with Kotlin coroutines and flows. In my scenario, a MutableStateFlow represents a connection state (CONNECTING, CONNECTED, CLOSING, CLOSED). It is also possible to login, logout and login again.

For further use of the connection, I have to check the state and wait until it is CONNECTED. If it is already CONNECTED, I can continue. If not, I have to wait until the state reaches CONNECTED. The connect() call does return immediately, the result is propagated via a callback that updates the MutableStateFlow. My current idea is to do the following:

connect()

if (connectionState.value != State.CONNECTED) { // connectionState = MutableStateFlow(State.CLOSED)

    suspendCoroutine<Boolean> { continuation ->
        scope.launch { // scope = MainScope()
            connectionState.collect {
                if (it == State.CONNECTED) {
                    continuation.resume(true)
                }
            }
        }
    }
}

// continue

As I am fairly new to the topic, I don't know if this is good practice and I was also not able to find a more suitable concept in the Kotlin documenation. Is there some better way of doing it?

Upvotes: 20

Views: 7454

Answers (1)

Animesh Sahu
Animesh Sahu

Reputation: 8096

A while back I had the same question:

enter image description here

It is preferred to use first() to suspend till the predicate is matched.

if (connectionState.value != State.CONNECTED) {
    connectionState.first { it == State.CONNECTED }
}

Upvotes: 29

Related Questions