How to expose events as flows

I think I’m starting to understand flows. If I want to process some text entered in an Android TextView, but only after the user hasn’t typed anything for a second, is this the right way to do it?

mainScope.launch {
    val flow = callbackFlow {
        val watcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                offer(s.toString())
            }
        }
        textView.addTextChangedListener(watcher)
        awaitClose()
    }
    flow.debounce(1000).collect { value ->
        processText(value)
    }
}
1 Like