https://kotlinlang.org logo
#compose
Title
# compose
j

james

02/02/2022, 9:02 PM
can anyone advise why my LaunchedEffect code block keeps triggering when coming back to my Composable, despite the key not changing? so my screen is composed, user navigates deeper, then comes back to that first screen using
navigateUp()
.. at this point the LaunchedEffect block is triggered again. am I misunderstanding it? code in thread ➡️
1
Copy code
@Composable
fun MyScreen(dataId: String, viewModel: MyViewModel = hiltViewModel()) {
    ...
    LaunchedEffect(key1 = dataId) {
        viewModel.load(dataId)
    }
    ...
}
I thought that if I come back to this screen using
navigateUp()
that nothing has changed (and I've confirmed that
dataId
has not changed) and so my
viewModel.load()
wouldn't be called again?
i

Ian Lake

02/02/2022, 9:37 PM
You are in a totally new composition when you come back (the previous composition was removed from the hierarchy as soon as the animation of it leaving finished)
It sounds like you should be doing one time work in your ViewModel's init, using the arguments that are automatically available to your ViewModel when it takes a SavedStateHandle as a parameter
j

james

02/02/2022, 9:43 PM
ahh okay.. follow up question on your suggested method: that requires me to always know the value upfront, but in my UX there is a way for the user to trigger a change to that value (for the same screen) and I want to reload at that point, rather than instantiate a new viewmodel altogether so let's say I change to your suggested method, can I do something like the following?:
Copy code
class MyViewModel(savedStateHandle: SavedStateHandle) {

  var dataId: String = ""

  init {
    dataId = savedStateHandle.get("dataId")
    // call load/refresh func
  }

  fun userTriggeredUpdate(newId: String) {
    dataId = newId
    savedStateHandle.set("dataId", dataId)
    // call load/refresh func
  }
}
or is there more I need to do within that
userTriggeredUpdate()
method to update the data inside
savedStateHandle
?
i

Ian Lake

02/02/2022, 9:53 PM
Yep, that'd work great
You could get more fancy (having the SavedStateHandle fill in a MutableStateFlow that you then transform into a flow that you actually fill the UI from), but the idea is the same
j

james

02/02/2022, 10:01 PM
awesome! this is really helpful, thanks a lot mate 🙏
alright I've moved it all across to what we discussed above and it works exactly as I'd hoped, thanks again Ian! 🎉
🎉 1
2 Views