Learning Kotlin Programming

Keep Your Kotlin Flow Alive and Listening With CallbackFlow

Make Your Cold Flow Hotter, By Keeping It Alive, And Understand CallbackFlow Easily

Photo by averie woodard on Unsplash

Flow is a much more powerful sequence of data handling mechanisms we have in Kotlin. It can do many things that normal sequence cannot do.

However, it is still limited by itself, as it only handles data emitted within the scope of its lambda as shown below.

fun main(): Unit = runBlocking {
flow {
for (i in 1..5) emit(i)
}.collect { println(it) }
}

Similarly, if we switch to Channel Flow

fun main(): Unit = runBlocking {
channelFlow {
for (i in 1..5) send(i)
}.collect { println(it) }
}

If we would like to send data at a later time, we can’t. 😞

fun main(): Unit = runBlocking {
channelFlow {
for (i in 1..5) send(i)
}.collect { println(it) }

--

--