https://kotlinlang.org logo
#flow
Title
# flow
a

abbic

09/26/2023, 12:03 PM
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

Filippo Vigani

09/26/2023, 3:44 PM
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

abbic

09/26/2023, 4:20 PM
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

Filippo Vigani

09/27/2023, 11:15 AM
SharedFlow
cannot be closed or cancelled by definition. It will be kept alive and the instance will be shared in your case
a

abbic

09/27/2023, 11:15 AM
baller, ty
12 Views