What’s the idiomatic way in Kotlin to handle event...
# getting-started
j
What’s the idiomatic way in Kotlin to handle events in non-UI code? In JS you declare an EventTarget, in Swift you use the delegate pattern. What could I use in Kotlin to be notified when a specific event occurs in a class instance? In Jetpack Compose, they have a simple
onClick
parameter for the
Button
class. My feeling here is there is no idiomatic way to handle events, am I wrong?
c
An object that emits events could expose a Flow, which observers could collect: https://kotlinlang.org/docs/flow.html There is #flow for this topic fyi
j
What if you emit an event without any data ? 🤔
d
Unit typed LiveData/Flow can be used for such things
v
I'm using Flow for this, MutableSharedFlow to be precise. And it's working good. And with Koin inject, it's pretty awesome.
K 2
j
So in my API I could create something like
Copy code
interface SomeInterface {
    val onSomeEvent: Flow<Unit>
}
And subscribe to it with collect?
Copy code
val someInstance: SomeInterface
someInstance.onSomeEvent.collect { println("Event received!") }
v
Copy code
sealed class AppEvent() {
    object EventWithoutData: AppEvent()
    data class EventWithData(val name: String) : AppEvent()
}
Copy code
eventFlow = MutableSharedFlow<AppEvent>()
j
Perfect, thank you all! 🙂