I'm trying to fetch current location from a (Compo...
# android
t
I'm trying to fetch current location from a (Compose) button using the following:
Copy code
scope.launch {
   val locationClient =
      LocationServices.getFusedLocationProviderClient(context)
   val location = await(locationClient.getCurrentLocation(PRIORITY_HIGH_ACCURACY, null))
   val target = LatLng(location.latitude, location.longitude)
   var update = CameraUpdateFactory.newLatLng(target)
   cameraState.animate(update, 300)
}
But I get an error ( java.lang.IllegalStateException: Must not be called on the main application thread) when I run this. I guess I thought the scope.launch would take care of that. I'm missing a bit of the magic with tasks/coroutines I think. What do I need to add/change to make that work?
c
How do you create the
scope
t
rememberCoroutineScope
c
ah, okay. yes, then the scope is on the main thread. either launch with
launch(<http://Dispatchers.IO|Dispatchers.IO>)
or use a
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
within the scope to switch the context to a background thread.
e
or
rememberCoroutineScope { <http://Dispatchers.IO|Dispatchers.IO> }