Lukasz Kalnik
08/12/2022, 9:40 AMsavedStateHandle
. Then I need to load data in the ViewModel based on the passed argument.
Do I get some callback when the ViewModel has been navigated to? How do I perform the initial data loading based on the navigation argument?Lukasz Kalnik
08/12/2022, 9:44 AMinit
block, it crashes, because it tries to access the navigation argument when the ViewModel is created in containing Fragment to be passed to the composable in the initial navigation graph setup.Lukasz Kalnik
08/12/2022, 10:04 AMclass SystemFragment : Fragment() {
private val sensorSettingsViewModel by viewModels<SensorSettingsViewModel>(
factoryProducer = { SensorSettingsViewModelFactory(this) }
)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return ComposeView(requireContext()).apply {
setContent {
DestinationsNavHost(
navGraph = NavGraphs.root
) {
composable(SensorSettingsSheetDestination) {
SensorSettingsSheet(
viewModel = sensorSettingsViewModel
)
}
}
}
}
}
}
Lukasz Kalnik
08/12/2022, 10:05 AMLukasz Kalnik
08/12/2022, 10:11 AMSystemFragment
, even without any actual navigation to the SensorSettingsSheet
):
class SensorSettingsViewModel(
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val navArgs: SensorSettingsSheetNavArgs = savedStateHandle.navArgs()
private val currentId: String = navArgs.sensorId
}
Lukasz Kalnik
08/12/2022, 10:13 AMRuntimeException: 'sensorId' argument is mandatory but was not present
Lukasz Kalnik
08/12/2022, 10:14 AMat myapp.systemoverview.presentation.destinations.SensorSettingsSheetDestination.argsFrom (SensorSettingsSheetDestination.kt:77)
Colton Idle
08/12/2022, 10:26 AMLukasz Kalnik
08/12/2022, 11:05 AMLukasz Kalnik
08/12/2022, 11:07 AMSensorSettingsSheetViewModel
gets constructed in SystemFragment.onCreateView()
even though there was no navigation to it (because I pass it to the composable).
I will test a delayed passing of viewmodels (as composable default argument), maybe it fixes the issue.Lukasz Kalnik
08/12/2022, 11:40 AMLukasz Kalnik
08/12/2022, 1:37 PMKoin
and passed them as default parameters to the composables:
val systemOverviewModule = module {
viewModel { SensorSettingsViewModel(savedStateHandle = get()) }
}
@Composable
fun SystemScreen(
viewModel: SystemViewModel = getViewModel(),
) {}
Lukasz Kalnik
08/12/2022, 1:38 PM