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.




Android Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

PAR and PPFD Meter Apps for Android: 2022 Edition

[Notice] 11/5 Surprise Coupon Number Event💌

Hands-on with Jetpack Compose

Convert Image URL to File format in Flutter

Reloading the laser!

How to use Play Install Referrer Library to keep track of Google Play Store downloads?

Track the Events by integration of Huawei Dynamic Tag Manager (DTM) in Android apps (Kotlin)

State of the art communication between fragments and their activity

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
efe budak

efe budak

Android Developer

More from Medium

Stackless Coroutine, Stackfulness Coroutine 區別簡單說明

DiffUtil in multiple columns list with different items

Jetpack Compose for Views developers — LinearLayout

Android Library Creation and Usage