Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Events not being delivered if posted in the init block #33

Open
Benjiko99 opened this issue May 30, 2021 · 1 comment
Open

Events not being delivered if posted in the init block #33

Benjiko99 opened this issue May 30, 2021 · 1 comment

Comments

@Benjiko99
Copy link

Benjiko99 commented May 30, 2021

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.

@zsmb13
Copy link
Member

zsmb13 commented Jul 8, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants