Compose w Google Maps: mapView.getMapAsync vs mapView.awaitMap in coroutine

Viewed 706

In the Crane jetpack compose sample they update a MapView in an AndroidView using a remembered coroutine.

val coroutineScope = rememberCoroutineScope()

AndroidView({ map }) { mapView ->
    coroutineScope.launch {
        val googleMap = mapView.awaitMap()
        // ...
    }
}

As an exercise I removed the coroutine and instead use the old getMapAsync

AndroidView({ map }) { mapView ->
    mapView.getMapAsync { googleMap ->
        // ...
    }
}

This appears to function correctly with the same performance, it also simplifies the code a little bit (no more need to remember a coroutine and arguably less mental gymnastics going between the old and new contexts).

Is there a hidden cost to doing this?

1 Answers

I believe I've figured it out.

As awaitMap is using a coroutine context it can be stopped/abandoned if its composition becomes invalid.

In contrast getMapAsync is a simple async operation with a callback. If the composition becomes invalid while the map is still being fetched, the operation will still continue and the callback will fire. This may lead to crashing if your callback makes assumptions about the state of your composition tree, nullable references, etc. so should not be used.

Related