Created
July 6, 2022 14:24
-
-
Save PiotrPrus/d65378c36b0a0c744e647946f344103c to your computer and use it in GitHub Desktop.
Some mapbox functions needed to use mapBox in Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Bundle | |
import androidx.compose.runtime.Composable | |
import androidx.compose.runtime.DisposableEffect | |
import androidx.compose.runtime.remember | |
import androidx.compose.ui.platform.LocalContext | |
import androidx.compose.ui.platform.LocalLifecycleOwner | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleEventObserver | |
import com.mapbox.mapboxsdk.maps.MapView | |
import com.mapbox.mapboxsdk.maps.MapboxMap | |
import kotlin.coroutines.resume | |
import kotlin.coroutines.suspendCoroutine | |
/** | |
* Remembers a MapView and gives it the lifecycle of the current LifecycleOwner | |
*/ | |
@Composable | |
fun rememberMapViewWithLifecycle(): MapView { | |
val context = LocalContext.current | |
val mapView = remember { MapView(context) } | |
// Makes MapView follow the lifecycle of this composable | |
val lifecycle = LocalLifecycleOwner.current.lifecycle | |
DisposableEffect(lifecycle, mapView) { | |
val lifecycleObserver = getMapLifecycleObserver(mapView) | |
lifecycle.addObserver(lifecycleObserver) | |
onDispose { | |
lifecycle.removeObserver(lifecycleObserver) | |
} | |
} | |
return mapView | |
} | |
private fun getMapLifecycleObserver(mapView: MapView): LifecycleEventObserver = | |
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() | |
} | |
} | |
suspend inline fun MapView.awaitMap(): MapboxMap = | |
suspendCoroutine { continuation -> | |
getMapAsync { | |
continuation.resume(it) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment