rainbowcake icon indicating copy to clipboard operation
rainbowcake copied to clipboard

Events not being delivered if posted in the init block

Open Benjiko99 opened this issue 4 years ago • 1 comments

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.

Benjiko99 avatar May 30 '21 11:05 Benjiko99

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.

zsmb13 avatar Jul 08 '21 18:07 zsmb13