How could I prevent a reload taking a parameter fr...
# compose
a
How could I prevent a reload taking a parameter from the composable on the viewModel on configuration change?
Copy code
Profile(userId: String) {
  val viewModel = hiltNavGraphViewModel<ProfileViewModel>()
  DisposableEffect(userId) {
    viewModel.loadProfile(userId) // don't trigger on config change
    onDispose { }
  }
  val profile = viewModel.profile.collectAsState(...)
}
Actually, with compose-navigation it seems the backstack arguments are also in the ViewModel savedStateHandle. I’m wondering if it would be better to extract the userId from there instead.
z
When you say config change, do you mean Android config change, like orientation? Is your activity configured to handle that itself or restart like normal?
a
Yes like orientation. There's no special activity configuration to handle it.
z
So your activity is being recreated, and the disposable effect is not running again in the new instance?
a
It is, but I'm trying to prevent that because the fetch already happened
In the samples they make use of the viewmodel(key) function with the key constructed with the param (like "the_viewmodel_$userId" and the fetch happens on init. So that kinda works. I can't do that since I'm using hilt, however
And without using ViewModels, not sure how's that gonna work with pure Compose. Perhaps a rememberSaveable booelan flag?
z
Ah - this seems like not a view layer problem. The view model instance is shared across activity recreations, right? So your view model probably needs some logic to say “oh I fetched this already, don’t need to fetch again I can just give you the cached value”
i
Yep, you'll want to move your
loadProfile
into the ViewModel if you only want to do it once and not on every config change
a
Yeah, I'm getting the arg from the composable from the compose nav now though, so I'm trying to figure out a way to pass it to the hilt viewmodel only once
z
You can still pass it to your view model every time, what I was saying was your ViewModel should be smart enough to know whether it needs to load or use a cached value.
So your communication between composition and view model becomes more “I’m showing this screen now, please load whatever data I’m going to need” rather than “please load this data” 👇
i
You don't even need to do that: args are already available to your ViewModel automatically via `SavedStateHandle`: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1616117339193100?thread_ts=1616114353.192500&amp;cid=CJLTWPH7S
a
Yeah, I guess a check within the viewModel would work.
i
Yeah, that's not necessary
a
Oh, right. I checked the sources beforehand and technically it supported that, I just wanted to confirm since I didn't see anyone else get it from the handle. Thanks Ian! Thank you as well Zach. If it weren't for the savedStateHandle, I'd try that instead