I'm trying to adapt this into my KMM project, but ...
# multiplatform
j
I'm trying to adapt this into my KMM project, but I'm not sure how to replace
lifecycleScope
with something I can use in KMM https://github.com/googlemaps/android-maps-compose/blob/d5533b47f407414ef27c47eefd[…]ava/com/google/maps/android/compose/LocationTrackingActivity.kt
this is the relevant part of the code, though I'm aiming to replace the infinite loop of random locations with a single location request
Copy code
private val locationFlow = callbackFlow {
    while (true) {
        ++counter

        val location = newLocation()
        Log.d(TAG, "Location $counter: $location")
        trySend(location)

        delay(2_000)
    }
}.shareIn(
    lifecycleScope,
    replay = 0,
    started = SharingStarted.WhileSubscribed()
)
ł
j
I think I was just overthinking things, I ended up launching a coroutine instead
Copy code
const val DEFAULT_ZOOM = 17f
val DEFAULT_LOC = LatLng(0.0, 0.0)

@Composable
@SuppressLint("MissingPermission")
actual fun Map(modifier: Modifier) {
    Setup()
    if (
        ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
    ) {
        Toast.makeText(
            appContext,
            "Location needs to be enabled to retrieve current location",
            Toast.LENGTH_SHORT
        ).show()
        return
    }

    val cameraPositionState = rememberCameraPositionState {
        position = CameraPosition.fromLatLngZoom(DEFAULT_LOC, DEFAULT_ZOOM)
    }
    val context = LocalContext.current
    val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
    val failureMessage = "Could not retrieve current location. Please try again later."

    fusedLocationClient.lastLocation.addOnSuccessListener { location ->
        location?.let { curLoc ->
            CoroutineScope(Dispatchers.Main).launch {
                val cameraPosition = CameraPosition.fromLatLngZoom(LatLng(curLoc.latitude, curLoc.longitude), DEFAULT_ZOOM)
                cameraPositionState.animate(CameraUpdateFactory.newCameraPosition(cameraPosition), 1_000)
            }
        } ?: run {
            Toast.makeText(context, failureMessage, Toast.LENGTH_SHORT).show()
        }
    }.addOnFailureListener { e ->
        Toast.makeText(context, failureMessage, Toast.LENGTH_SHORT).show()
        e.message?.let { Log.e({}.javaClass.enclosingMethod?.name, it) }
    }

    GoogleMap(
        modifier = modifier.fillMaxSize(),
        cameraPositionState = cameraPositionState,
        properties = MapProperties(isMyLocationEnabled = true)
    )
}