Android User Events to Kotlin Flow

Photo by Roman Synkevych on Unsplash


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

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

Android Developer

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