Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To stop or unsubscribe from a Kotlin Flow, you can call the cancel() function on the corresponding Job object that was returned when you started collecting the flow:

val job = launch {
    someFlow.collect {
        // do something with the emitted value
    }
}

// to unsubscribe:
job.cancel()

Alternatively, you can use the onCompletion, onError or catch operators to handle the completion or error of the flow and perform any necessary cleanup:

someFlow
    .onCompletion {
        // cleanup code
    }
    .onError { 
        // handle error and cleanup code
    }
    .catch { 
        // handle exception and cleanup code
    }
    .collect {
        // do something with the emitted value
    }