Would it be safe to expose a `Flow` from a custom ...
# android
b
Would it be safe to expose a
Flow
from a custom view or could this cause leaks?
g
Depends on what this flow does and how it implemented
b
It's a custom view with an EditText where a TextWatcher listens for changes and emit when changes are made to the text.
Copy code
kotlin
@ExperimentalCoroutinesApi
    val textWatcher: Flow<CharSequence> = callbackFlow {
        custom_inputview_text_input_edit_text.addOnTextChangedListener {
            afterTextChanged { s -> Timber.d("AfterTextChanged: $s") }
            beforeTextChanged { text, start, count, after -> Timber.d("BeforeTextChanged: $text") }
            onTextChanged { text, start, before, count -> Timber.d("Within $text, the $count characters beginning at $start have just replaced old text that had length $before.") }
        }
    }
The listener is a
Presenter
that is attached to a
Fragment
in
onActivityCreated()
and detached in
onDestroy()
g
It will leak
also because flow is lazy you can attempt to consume this flow when view already detached
to avoid it you have to subscribe after onViewCreated and detach onDestroyView
đź‘Ť 1
b
I thought so.
subscribe after onViewCreated and detach onDestroyView
Afraid this will lead to other issues.
g
it’s not unique for Flow
but otherwise your view will leak, that’s the problem
actually it’s pretty easy to implement, you should collect your flow only in coroutine launched in viewLifecycleObserver.coroutineScope, which will be cancelled automatically on view destroy
r
To be honest , it's never a good idea to have logic in your views
b
So if my
Presenter
would implement
(Default)LifecycleObserver
and start observing
viewLifecycle
of the
Fragment
it would be possible to avoid leaking the view?
It would cancel
collect
when the `Fragment`s view gets destroyed?
g
No, Presenter cannot implement it
I mean it can, but it's not what I propose, if presenter implements scope it still should know somehow about view lifecycle, but only fragment knows this
b
@gildor When you say
viewLifecycleObserver.coroutineScope
Do you mean the new
lifecycleOwner.lifecycleScope
-API that is released in lifecycle-runtime-ktx:2.2.0-alpha01?
g
Yes, this API, but I mean specifically fragment.viewLifecycleObserver property, which provided by Fragment and has a lifecycle of view, not a lifecycle of Fragment
b
Thanks. I'll take a look at it.