functions in Android (which get triggered from non-UI events) and you suddenly find you need a
Context
to get something done (in this instance load a preference value), what are sound approaches to adopt? I understand that storing
Context
references is a no-no, due to the potential to leak Activites.
a
Adam Powell
04/15/2021, 3:45 PM
letting the coroutine capture a reference to the application context only and not the activity context is one way, but without some more details it's hard to get more precise about recommended patterns.
z
Zach Klippenstein (he/him) [MOD]
04/15/2021, 3:45 PM
Structurred concurrency can help here β if you are using it correctly, and are confident that the coroutine wonβt live beyond the lifetime of the activity, it should be fine.
βοΈ 6
a
Adam Powell
04/15/2021, 3:54 PM
Right. If you're consuming a cold Flow of non-UI events (e.g. from a
Channel.receiveAsFlow()
) from an activity-scoped context, you're still in good shape.
Adam Powell
04/15/2021, 3:56 PM
Crucially, this sort of thing is a reason to use
Channel.receiveAsFlow
and not
MutableSharedFlow
for events that must be handled exactly once.
SharedFlow
creates a diffusion of responsibility that you then have to resolve elsewhere where it can be much more difficult.