Android User Events to Kotlin Flow

efe budak
2 min readDec 13, 2020
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.

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, 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) {}
}
editTextSearch.addTextChangeListener(textWatcher)
awaitClose { editTextSearch.removeTextChangedListener(textWatcher)
}
typingFlow
.filter { typedText -> typedText.length > 2 }
.debounce(2000)
.collect { typedText -> someRepository.fetchSuggestions(typedText) }

I would recommend the following post for further details for the Kotlin flows. https://elizarov.medium.com/callbacks-and-kotlin-flows-2b53aa2525cf

Let me know if anything is unclear or wrong.

--

--