Is there a way to persist the state of a MapView ...
# compose
m
Is there a way to persist the state of a MapView with compose? I am using bottom navigation where one of the tabs contains a mapview. But every time I go to another tab and go back to the map tab, the map gets re-compose and I lose the state. I am using these helper methods: ``````
r
I had this exact problem and solved it with:
Copy code
val state by rememberSaveable(key = "mapState") {
        mutableStateOf(Bundle())
    }
and pass it to onCreate:
Copy code
Lifecycle.Event.ON_CREATE -> mapView.onCreate(state)
otherwise you are always creating a new bundle and losing its state
c
@MRSasko Could you edit your question to put more of it in the thread? See: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1616265877303000
m
The code: example:
Copy code
@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()
            }
        }
    }
🙏 1
@rattleshirt It’s not working when I save the Bundle. I could save all of the MapState(zoom, cameraTarget) and so, into a MapViewModel?