Android User Events to Kotlin Flow

Photo by Roman Synkevych on Unsplash

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.


callbackFlow is the extension function that is used.

val addClickFlow = callbackFlow {
buttonAdd.setOnClickListener {
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

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, filter, debounce, onEach, reduce and many more. Have a look at the Extention Functions part.

Here is our typingFlow ;

val typingFlow = callbackFlow {
val textWatcher = object: TextWatcher{
override fun afterTextChanged(editable: Editable?) {
editable?.toString()?.let{ offer(it)}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
awaitClose { editTextSearch.removeTextChangedListener(textWatcher)
.filter { typedText -> typedText.length > 2 }
.collect { typedText -> someRepository.fetchSuggestions(typedText) }

I would recommend the following post for further details for the Kotlin flows.

Let me know if anything is unclear or wrong.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store