From c72d4e7a3a08cf7d29327317db68dc532408bcf2 Mon Sep 17 00:00:00 2001 From: Shobhit Agarwal Date: Sat, 7 Oct 2023 20:03:49 +0530 Subject: [PATCH] Allow zooming in to the current location when toggling the lock 2nd time (#1957) * Allow zooming in to the location on 2nd location lock enable * Reset location updates flow when location lock and disabled and undo the logic for panAndZoom at index 0 --- .../ground/ui/common/BaseMapViewModel.kt | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/ground/src/main/java/com/google/android/ground/ui/common/BaseMapViewModel.kt b/ground/src/main/java/com/google/android/ground/ui/common/BaseMapViewModel.kt index 42e18486b4..aa724ff3ab 100644 --- a/ground/src/main/java/com/google/android/ground/ui/common/BaseMapViewModel.kt +++ b/ground/src/main/java/com/google/android/ground/ui/common/BaseMapViewModel.kt @@ -46,12 +46,16 @@ import com.google.android.ground.ui.map.gms.GmsExt.toBounds import com.google.android.ground.ui.map.gms.toCoordinates import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.transform @@ -96,7 +100,7 @@ constructor( val location: StateFlow = locationLock - .combine(locationManager.locationUpdates) { locationLock, latestLocation -> + .combine(getLocationUpdates()) { locationLock, latestLocation -> if (locationLock.getOrDefault(false)) { latestLocation } else { @@ -197,16 +201,21 @@ constructor( /** Emits a stream of current camera position. */ fun getCurrentCameraPosition(): Flow = currentCameraPosition.filterNotNull() - fun getLocationUpdates() = locationManager.locationUpdates + fun getLocationUpdates() = locationManager.locationUpdates.distinctUntilChanged() /** * Updates map camera when location changes. The first update pans and zooms the camera to the * appropriate zoom level and subsequent ones only pan the map. */ + @OptIn(ExperimentalCoroutinesApi::class) private suspend fun updateCameraPositionOnLocationChange() { - getLocationUpdates() - .map { it.toCoordinates() } - .withIndex() + locationLock + .flatMapLatest { enabled -> + getLocationUpdates() + .map { it.toCoordinates() } + .filter { enabled.getOrDefault(false) } + .withIndex() + } .collect { (index, coordinates) -> if (index == 0) { panAndZoomCamera(coordinates)