Ask Your Question
4

What is the process to stop or unsubscribe from Kotlin Flow?

asked 2022-05-05 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-03 06:00:00 +0000

devzero gravatar image

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
    }
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-05 11:00:00 +0000

Seen: 6 times

Last updated: Oct 03 '21