Hi, I'm implementing an EventBus for my app using ...
# flow
a
Hi, I'm implementing an EventBus for my app using a SharedFlow like so
Copy code
@Singleton
class AppEventBus @Inject constructor() {
    private val internalSharedFlow =
        MutableSharedFlow<AppEvent>()
    val allEvents: Flow<AppEvent> get() = internalSharedFlow

    inline fun <reified T: AppEvent> observe(): Flow<T> =
        allEvents.filterIsInstance()

    fun tryPostEvent(event: AppEvent) {
        internalSharedFlow.tryEmit(event)
    }

    suspend fun postEvent(event: AppEvent) {
        internalSharedFlow.emit(event)
    }
}
I threw it together in 5 minutes so im sure i can make many improvements, bust specifically i was wondering, given that this class will be a singleton, can I rely on the flow staying alive on its own for the lifecycle of the program? sorry if its a strange question, i am probably worrying about nothing
f
It depends on the component that contains the singleton scope. By default it should be the AppComponent, hence the instance's lifecycle will last as long as the app is alive
a
good point, i meant implicitly that the bus would be installed in the app scope. the question is more is there a risk that the flow lives less long than whatever scope it is installed in, though im now thinking a flow just cant be cancelled the same way a coroutine can be
f
SharedFlow
cannot be closed or cancelled by definition. It will be kept alive and the instance will be shared in your case
a
baller, ty
144 Views