https://kotlinlang.org logo
#android
Title
# android
b

bohsen

09/03/2019, 8:59 AM
Would it be safe to expose a
Flow
from a custom view or could this cause leaks?
g

gildor

09/03/2019, 9:24 AM
Depends on what this flow does and how it implemented
b

bohsen

09/03/2019, 9:40 AM
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

gildor

09/03/2019, 10:17 AM
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

bohsen

09/03/2019, 10:55 AM
I thought so.
subscribe after onViewCreated and detach onDestroyView
Afraid this will lead to other issues.
g

gildor

09/03/2019, 11:42 AM
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

rkeazor

09/03/2019, 12:02 PM
To be honest , it's never a good idea to have logic in your views
b

bohsen

09/03/2019, 12:22 PM
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

gildor

09/03/2019, 2:31 PM
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

bohsen

09/03/2019, 7:28 PM
@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

gildor

09/03/2019, 11:24 PM
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

bohsen

09/04/2019, 5:40 AM
Thanks. I'll take a look at it.
8 Views