Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Kotlin flow when certain condition occurs

I want to cancel kotlin flow if certain condition occurred in code.

Suppose i have a method as following

fun test(): Flow<String> = flow {
    val lst = listOf("A", "B", "C")

    while(true) {
        lst.forEach { emit(it) }

    //If some condition occurs, need to return from here, else continue
    //How to stop flow here
    }
}

and calling it like

test().collect { println(it)}

question is, how to stop flow to produce anything on certain conditions (from flow builder or outside of it)?

like image 802
Rajesh Avatar asked Sep 01 '25 10:09

Rajesh


1 Answers

fun test(): Flow<String> = flow {
    val lst = listOf("A", "B", "C")

    while(true) {
        lst.forEach { emit(it) }

        if (someCondition) {
            return@flow
        }
    }
}

return@flow instantly returns from flow lambda, so the flow will be ended. As another option, you can just break your while(true) loop when your condition occurs.

like image 115
ardenit Avatar answered Sep 03 '25 00:09

ardenit