airbnb / mavericks

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

Is there a way to get the MavericksViewModel to refresh when returning to a Fragment? #667

Closed martymiller closed 1 year ago

martymiller commented 1 year ago

I find that when I go back to a Fragment, I'm looking at stale data. I want the ViewModel to refetch all of the latest data without the Fragment telling it to. Seems like this would be possible given that the viewmodel is lifecycle aware. Is this possible?

elihart commented 1 year ago

I'm not really sure what you mean. You want the viewmodel to execute network requests when the Fragment hits resumed or started states?

A ViewModel is only lifecycle aware in so far as it gets destroyed when its parent scope is destroyed. Besides that it isn't aware of the view lifecycle of a Fragment in the UI. if you want to refresh data you can invoke a function on the viewmodel to do so from the fragment's onStart function

martymiller commented 1 year ago

Got it, thanks. I was just wondering how other apps handles this.

For example, say you navigate from Fragments A -> B -> C and then make a change in C. When you navigate back, you want to see that change reflected in Fragment B, and then also see that change when going back to A.

The ViewModel typically fetches data when initialized, so you don't want the Fragment's onStart() to also tell it to fetch data and make double calls. I ended up adding this to my fragment's onStart().

(from my viewModel)

  internal fun maybeRefresh() = withState { state ->
    if(state.bookingsResponse.isSuccess()) {
      getBookings()
    }
  }

Is this how devs typically handle it? I didn't want to use a fragmentResultListener or backstack listener. That gets too messy imho.

elihart commented 1 year ago

you could have your viewmodels communicate so that ViewModel B knows when C has a change

martymiller commented 1 year ago

I didn't know that was possible. Is that a Maverick's feature? What would be the mechanism that tells C to change?