I’m trying to create a flow from an EditText chang...
# coroutines
m
I’m trying to create a flow from an EditText change in Android, I’m using
flow {…}
builder, So I’m creating a watcher inside it here is the code, my question is how I clear inner listeners when flow canceled ?
Copy code
fun EditText.textChangesFlow(): Flow<TextViewTextChangeEvent> {
    flow<TextViewTextChangeEvent> {
        val watcher = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                emit(TextViewTextChangeEvent(s.toString()))
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        }
        addTextChangedListener(watcher)
         //how to call this when flow is canceled or finished
        //removeTextChangedListener(watcher)

    }
}
s
Add an
awaitClose { … clear inner listeners here … }
at the end of your
flow { … }
lambda:
Copy code
flow<TextViewTextChangedEvent> {
    ...
    ...
    awaitClose { removeTextChangedListener(watcher) }
  }
👍 1
k
You must use
channelFlow
not
flow
. Within the scope of channelFlow you can use awaitClose. You must also change
emit
to
send
Copy code
channelFlow<TextViewTextChangedEvent> {
    ...
    ...
    awaitClose { removeTextChangedListener(watcher) }
  }
👍 2
m
Do I need to make
textChangesFlow
suspend function, I have a compile error with
send()
and
emit()
k
The scope inside channel flow should be suspend. So I wouldn't think so
s
But the callback
afterTextChanged
is not suspend. So yes, either use
offer(…)
or wrap it inside a launch:
launch { send(…) }
.
m
I used
launch{...}
but is it safe to call?
s
Not sure what you mean by ‘safe’?
But creating Coroutines (using launch or async) is cheap, if you were worrying about that.
t
I'd suggest using
callbackFlow
instead of
channelFlow
. While both provide exactly the same behavior,
callbackFlow
makes the intent clearer in this case. Also, since 1.3.4 there is a lint warning with
callbackFlow
that notifies you if you forget about
awaitClose
.
💯 3
d
239 Views