Skip to content

Flow: Terminal operators

Devrath edited this page Dec 25, 2023 · 20 revisions
Terminal Operators
First
Last

First

Observation

  • You can notice that we have used first operator.
  • Also, even the second edition has not happened, so emission stops after the first emission.
  • The flow is canceled once the first emission is received.
  • If there are no elements then it would throw java.util.NoSuchElementException: To prevent this we can use firstOrNull instead of just first

Code

@HiltViewModel
class TerminalOperatorsVm @Inject constructor(
    @ApplicationContext private val context: Context,
) : ViewModel() {
    companion object {
        const val emissionDelay : Long = 100
    }

    private val terminalOperatorDemo = flow {
        delay(emissionDelay)
        println("Emitting first value")
        emit(1)
        delay(emissionDelay)
        println("Emitting second value")
        emit(2)
    }

    /** *********************** DEMO's *********************** **/
    /**
     * Terminal Operator: First
     */
    fun demoFirst() {
        viewModelScope.launch {
            val result = terminalOperatorDemo.first()
            println("Result:-> $result")
        }
    }

    /** *********************** DEMO's *********************** **/
}

Output

Emitting first value
Result:-> 1

Last

Observation

  • Here also observe that all the emissions are done from the flow but only the last emission is received in flow

Code

@HiltViewModel
class TerminalOperatorsVm @Inject constructor(
    @ApplicationContext private val context: Context,
) : ViewModel() {
    companion object {
        const val emissionDelay : Long = 100
    }

    private val terminalOperatorDemo = flow <Int>{
        delay(emissionDelay)
        println("Emitting first value")
        emit(1)
        delay(emissionDelay)
        println("Emitting second value")
        emit(2)
    }

    /** *********************** DEMO's *********************** **/

    fun demoLast() {
        viewModelScope.launch {
            val result = terminalOperatorDemo.lastOrNull()
            println("Result:-> $result")
        }
    }

    /** *********************** DEMO's *********************** **/
}

Output

Emitting first value
Emitting second value
Result:-> 2
Clone this wiki locally