Hi there. I wonder if it is a good idea to use a `MutableSharedFlow` as an app wide event bus for a ...
s
Hi there. I wonder if it is a good idea to use a
MutableSharedFlow
as an app wide event bus for a reactive architecture. Does anything speak against it? Does it stay stable if the app is kept open all day long and is repeatedly put into foreground/background?
🚫 1
@Adam Powell do you mind to elaborate why this is not a good idea?
a
app-wide event buses tend to be a bad idea in general and lead to difficult to diagnose bugs around scoping, ordering and subscription management
s
@Adam Powell i absolutely agree with that. But say i have no choice, instead of using a 3rd party bus library, any reason not to use
MutableSharedFlow
?
a
if you have flows available it would be better to use them in more effective ways than emulating a pattern that incurs a lot of technical debt
c
app wide event bus always spirals into terrible-ness. but what about storing some app wide state? for example. app wide we keep track of login state
s
yes that is a good example. i might have dug myself into a bit of a hole by calling it an app wide bus. so say, i have a module that exposes the login state as a
Flow
(backed by a
MutableSharedFlow
). The question is if that flow stays stable over an extended period of time and several app backgrounds/foregrounds or if i had to resubscribe to it
a
there are several angles to that question. What does "stable" mean? An active collector/subscriber will continue to collect the flow unless cancelled or the flow ends, and a
MutableSharedFlow
isn't going to end since
SharedFlow
never completes
an android app in the background is just a process. If something is still running, it will continue to do so unless the system decides to kill the process. If that happens, it's a
kill -9
and the whole process is terminated, there's no cancellation or callback or graceful exit involved
if the process is killed then there's no more flow or collector at all
but android isn't going to selectively mess with a flow collector without also killing the rest of your process along with it. You can use things like the
flowWithLifecycle
operator in the androidx lifecycle libraries to stop collecting an upstream flow when a given
Lifecycle
is stopped, which can be used to intentionally unsubscribe while some part of your app is in the background, but this won't happen out from under you. You have to opt-in by assembling those flow operators yourself
s
awesome, thanks a lot for the information @Adam Powell. This is pretty much what i've assumed. I just wanted confirmation. also thank you both for the speeches against event busses. that brought me back to reality 😉
👍 1