Events not being delivered if posted in the init block
Events that are posted synchronously from within the ViewModel's init block are never delivered to the Activity/Fragment.
The Activity has not yet started observing the events at this point (while the ViewModel class is being created), but they are not queued up and delivered even once observing begins.
Relevant code in RainbowCakeActivity
override fun onCreate(savedInstanceState: Bundle?) {
viewModel = provideViewModel()
viewModel.events.observe(this) { event ->
event?.let { onEvent(it) }
}
viewModel.queuedEvents.observe(this) { event ->
event?.let { onEvent(it) }
}
}
class MyViewModel :
RainbowCakeViewModel<MyViewState>(MyViewState.Content()) {
object MyEvent : QueuedOneShotEvent
init {
postQueuedEvent(MyEvent)
}
}
class MyActivity : RainbowCakeActivity<MyViewState, MyViewModel>() {
override fun provideViewModel() = getViewModelFromFactory()
override fun render(viewState: MyViewState) {}
// WTF: onEvent is never called !!!
override fun onEvent(event: OneShotEvent) {
when (event) {
is MyEvent -> {
Toast.makeText(this, "MyEvent received", Toast.LENGTH_LONG).show()
}
}
}
}
A workaround is to call postEvent() from within a execute block, giving the Activity enough time to start observing the events.
This is correct, I'll look into providing a good solution to this. It will very rarely come up as a use case though. Usually events happen in reaction to something happening. If you always need to do something on init, there are other ways to do it.