When using `suspend` functions in Android (which g...
# coroutines
a
When using
suspend
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
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
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
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.
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.
👍 1
a
Many thanks to you all for the input! 👍
👍 1