diff --git a/android/src/main/java/com/rnmapbox/rnmbx/components/camera/RNMBXCamera.kt b/android/src/main/java/com/rnmapbox/rnmbx/components/camera/RNMBXCamera.kt index 2ecc171cd..30658b05c 100644 --- a/android/src/main/java/com/rnmapbox/rnmbx/components/camera/RNMBXCamera.kt +++ b/android/src/main/java/com/rnmapbox/rnmbx/components/camera/RNMBXCamera.kt @@ -91,9 +91,11 @@ class RNMBXCamera(private val mContext: Context, private val mManager: RNMBXCame override fun addToMap(mapView: RNMBXMapView) { super.addToMap(mapView) - setInitialCamera() - updateMaxBounds() - mCameraStop?.let { updateCamera(it) } + mapView.callIfAttachedToWindow { + setInitialCamera() + updateMaxBounds() + mCameraStop?.let { updateCamera(it) } + } _observeViewportState(mapView.mapView) _updateViewportState() } diff --git a/android/src/main/java/com/rnmapbox/rnmbx/components/mapview/RNMBXMapView.kt b/android/src/main/java/com/rnmapbox/rnmbx/components/mapview/RNMBXMapView.kt index e42403634..049eda350 100644 --- a/android/src/main/java/com/rnmapbox/rnmbx/components/mapview/RNMBXMapView.kt +++ b/android/src/main/java/com/rnmapbox/rnmbx/components/mapview/RNMBXMapView.kt @@ -4,6 +4,8 @@ import android.content.Context import android.graphics.BitmapFactory import android.graphics.PointF import android.graphics.RectF +import android.os.Handler +import android.os.Looper import android.util.Log import android.view.Gravity import android.view.View @@ -102,6 +104,10 @@ interface RNMBXLifeCycleOwner : LifecycleOwner { fun handleLifecycleEvent(event: Lifecycle.Event) } +fun interface Cancelable { + fun cancel() +} + class RNMBXLifeCycle { private var lifecycleOwner : RNMBXLifeCycleOwner? = null @@ -150,6 +156,25 @@ class RNMBXLifeCycle { fun getState() : Lifecycle.State { return lifecycleOwner?.lifecycle?.currentState ?: Lifecycle.State.INITIALIZED; } + + var attachedToWindowWaiters : MutableList<()-> Unit> = mutableListOf() + + fun callIfAttachedToWindow(callback: () -> Unit) : com.rnmapbox.rnmbx.components.mapview.Cancelable { + if (getState() == Lifecycle.State.STARTED) { + callback() + return com.rnmapbox.rnmbx.components.mapview.Cancelable {} + } else { + attachedToWindowWaiters.add(callback) + return com.rnmapbox.rnmbx.components.mapview.Cancelable { + attachedToWindowWaiters.removeIf { it === callback } + } + } + } + + fun afterAttachFromLooper() { + attachedToWindowWaiters.forEach { it() } + attachedToWindowWaiters.clear() + } } data class FeatureEntry(val feature: AbstractMapFeature?, val view: View?, var addedToMap: Boolean = false) { @@ -1418,6 +1443,13 @@ open class RNMBXMapView(private val mContext: Context, var mManager: RNMBXMapVie override fun onAttachedToWindow() { lifecycle.onAttachedToWindow(this) super.onAttachedToWindow() + Handler(Looper.getMainLooper()).post { + lifecycle.afterAttachFromLooper() + } + } + + fun callIfAttachedToWindow(callback: () -> Unit) { + lifecycle.callIfAttachedToWindow(callback) } override fun onLayoutChange(