How to throw Exception when SharedFlow does not contain item

39 views Asked by At

I need to check that SharedFlow contain some item. And throw NoSuchElementException when this element is absent.

I'm writed some code below, it work perfect when SharedFlow contain item. But if this element is absent code just waiting all the time.

private val _sharedFlow = MutableSharedFlow<String>()

// fill _sharedFlow with some states
private suspend fun emitStates() {
    _sharedFlow.emit("START")
    delay(100)
    _sharedFlow.emit("FIRST")
    delay(100)
    _sharedFlow.emit("SECOND")
    delay(100)
    _sharedFlow.emit("ENDING")
    delay(100)
    _sharedFlow.emit("IDLE")
}


private suspend fun awaitState(state: String) {
    _sharedFlow.filter {
                incomingState -> incomingState == state
            }
            .onCompletion {
                Log.d(TAG, "onCompletion()")
            }
            .onEmpty {
                Log.d(TAG, "onEmpty()")
            }
            .firstOrNull()
}

RUN PROGRAM WITH SUCCESS:

private suspend fun waitSecond() {
    // waiting for "SECOND"
    awaitState("SECOND")
    // run other code after getting "SECOND"
}

RUN PROGRAM WITH FAILED:

private suspend fun waitSomeString() {
    try {
        // waiting for "Some" all the time
        awaitState("Some")
    } catch(e: Exception) {
        // catch NoSuchElementException 
        // run other code after Exception
    }
}
0

There are 0 answers