MRSasko
01/21/2022, 7:45 AMrattleshirt
01/21/2022, 8:07 AMval state by rememberSaveable(key = "mapState") {
mutableStateOf(Bundle())
}
and pass it to onCreate:
Lifecycle.Event.ON_CREATE -> mapView.onCreate(state)
otherwise you are always creating a new bundle and losing its stateColton Idle
01/21/2022, 8:07 AMMRSasko
01/21/2022, 8:24 AM@Composable
fun rememberMapViewWithLifecycle(): MapView {
val context = LocalContext.current
val mapView = remember {
MapView(context).apply {
id = R.id.map
}
}
// Makes MapView follow the lifecycle of this composable
val bundle = Bundle()
val lifecycleObserver = rememberMapLifecycleObserver(mapView, bundle)
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycle.removeObserver(lifecycleObserver)
}
}
return mapView
}
@Composable
private fun rememberMapLifecycleObserver(mapView: MapView, bundle: Bundle): LifecycleEventObserver =
remember(mapView) {
LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_CREATE -> mapView.onCreate(bundle)
Lifecycle.Event.ON_START -> mapView.onStart()
Lifecycle.Event.ON_RESUME -> mapView.onResume()
Lifecycle.Event.ON_PAUSE -> mapView.onPause()
Lifecycle.Event.ON_STOP -> mapView.onStop()
Lifecycle.Event.ON_DESTROY -> mapView.onDestroy()
else -> throw IllegalStateException()
}
}
}