airbnb / mavericks

Mavericks: Android on Autopilot
https://airbnb.io/mavericks/
Apache License 2.0
5.85k stars 499 forks source link

The viewModel() method may be missing the postInvalidate() logic. #690

Open weijia1991 opened 1 year ago

weijia1991 commented 1 year ago

In activity by viewModel() is not working properly, the invalidate() method doesn't callback when the viewLifecycleOwner is started, viewModel() is missing the postInvalidate() logic like activityViewModel(), please tell me how should I do it in activity. Can I modify the viewModel() code like this:

inline fun <T, reified VM : MavericksViewModel<S>, reified S : MavericksState> T.viewModel(
    viewModelClass: KClass<VM> = VM::class,
    crossinline keyFactory: () -> String = { viewModelClass.java.name }
): Lazy<VM> where T : ComponentActivity, T : MavericksView = lifecycleAwareLazy(this) {
    val lifecycleOwner = this
    MavericksViewModelProvider.get(
        viewModelClass = viewModelClass.java,
        stateClass = S::class.java,
        viewModelContext = ActivityViewModelContext(this, intent.extras?.get(Mavericks.KEY_ARG)),
        key = keyFactory()
    ).apply { _internal(lifecycleOwner, action = { lifecycleOwner.postInvalidate() }) }
}
hezd commented 1 year ago

I'm experiencing the same issue, is it because it's not recommended for use in Activity and therefore doesn't provide a solution?

YumengNevix commented 1 year ago

invalidate function has comment: "Override this to handle any state changes from MavericksViewModels created through Mavericks Fragment delegates." so this method is just used in Fragment class. If you want to observe state change in Activity, you can use :

viewModel.onEach(State::property) {
   // refresh ui
}