Eric Martori
02/01/2022, 4:53 PMid
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:
@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?