I am trying to create a simple list -> details ...
# compose
e
I am trying to create a simple list -> details app to use as a template to try new things. But I am having issues with my current approach. I have the following setup: MainActivity: Call the App Composable App Composable: Contains a NavHost with the list and details destinations, the details destination has an
id
parameter ItemViewModel: An AAC ViewModel that loads the list of items on init and has a
requestItem
method that loads the details of the corresponding item. DI made in Koin with the ViewModel injected in the composables for both screens I have some issues but the main one is as follows: I want the Details composable to be self contained and without any setup required from other composables to open it. To achieve this I have the following:
Copy code
@Composable
fun Details(id: String, viewModel: ItemViewModel = getViewModel()) {
  val item by viewModel.currentItem.collectAsState(initial = null)
  LaunchedEffect(id) {
    viewModel.requestItem(id)
  }
  Details(item)
}
This works, until there is a configuration change, when there is a configuration change the MainActivity get recreated, the composables get composed again and the LaunchedEffect is called again. This is a toy project and is not and big issue to recall the
requestItem
method, but this smells like trouble if I try to apply the same pattern in an app intended for production. I haven't found any approach online that helps for this problem, most solutions online tell to move the call into the
init
of the ViewModel, but this wouldn't help in this case since the parameter is needed and creating a new ViewModel for each Detail screen would be an issue in and of itself. I am open to solutions that require big changes as long as the meet the following requirements: • The Details composable should be able to be opened without any setup from the caller side (i.e. Calling
requestItem
before navigating is not an option) • The ViewModel instance (if ViewModels are used) has to be shared by all Details composables (Recreating the ViewModel instance for each Details screen is not an option) • Configuration changes and recompositions must not relaunch the
requestItem
method unless
id
changes, in that case
requestItem
must be called with the new
id
Is what I am asking possible?