Kotlin flow has become a new tool in our android development toolkit that is promoted by Google. It is fun to learn and use as well. So, it is what I’m doing recently.
This post is not a Kotlin flow tutorial at all. This post is focusing only on how to convert user events into Kotlin flow objects to have more power over them.
How;
callbackFlow is the extension function that is used.
val addClickFlow = callbackFlow {
buttonAdd.setOnClickListener {
offer(Unit)
}
awaitClose { buttonAdd.setOnClickListener(null) }
}
That’s it. Simple enough. After this point, you can use that flow object as you want.
val addClickFlow.collect{ userClick: Unit ->
// it is guaranteed that you'll get all the user clicks since
// a flow is a cold asynchronous stream of multiple values
doSomeFunCalls()
}
It does not look that useful at all for user clicks, to be honest. But hey! It is a start. Let’s see a scenario that callbackFlow is super useful. (At least it was for me.)
User typing event;
Typing event is more like it. It is super useful to have the typing event as a stream of multiple values. There are multiple extension functions you can use such as; map
…