Android User Events to Kotlin Flow

Photo by Roman Synkevych on Unsplash

How;

val addClickFlow = callbackFlow {
buttonAdd.setOnClickListener {
offer(Unit)
}
awaitClose { buttonAdd.setOnClickListener(null) }
}
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()
}

User typing event;

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) }

Android Developer @Teckro.com

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