From 54e67e0447acbcb34f16b93289bad5eaa27b42eb Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 21 Nov 2026 11:34:45 -0800 Subject: [PATCH] Hand over states added to a mutableStateListOf in place Markers, Circles, Polylines and Polygons handed their list to the map again only when given a different list. A mutableStateListOf that the app adds to stays the same list, so a pin-per-tap screen logged one more marker per tap and drew none. Each now also follows in-place changes to a SnapshotStateList, copying it on the main thread so the work on Dispatchers.Default never reads it while the app changes it. --- .../com/mapconductor/compose/ListVersions.kt | 37 ++++ .../compose/circle/CircleCompose.kt | 54 +++--- .../compose/marker/MarkerCompose.kt | 58 +++--- .../compose/polygon/PolygonComponent.kt | 46 +++-- .../compose/polyline/PolylineComponent.kt | 36 ++-- .../mapconductor/compose/InPlaceListTest.kt | 183 ++++++++++++++++++ 6 files changed, 325 insertions(+), 89 deletions(-) create mode 100644 src/main/java/com/mapconductor/compose/ListVersions.kt create mode 100644 src/test/java/com/mapconductor/compose/InPlaceListTest.kt diff --git a/src/main/java/com/mapconductor/compose/ListVersions.kt b/src/main/java/com/mapconductor/compose/ListVersions.kt new file mode 100644 index 0000000..6a6263f --- /dev/null +++ b/src/main/java/com/mapconductor/compose/ListVersions.kt @@ -0,0 +1,37 @@ +package com.mapconductor.compose + +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.snapshots.SnapshotStateList +import com.mapconductor.core.InternalMapConductorApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map + +/** + * [list] now and, when it is a `mutableStateListOf`, again after each change + * made to it in place. + * + * `Markers(states)`, `Circles(states)`, `Polylines(states)` and + * `Polygons(states)` hand their list to the map again when they are given a + * different list. A `mutableStateListOf` that the app adds to is the same list + * every time, so the states added after the first hand-over never reached the + * map: a pin per tap logged one more marker per tap and drew none. + * + * Each version is a copy taken on the main thread, so the work done with it on + * another thread never reads the list while the app is changing it. + */ +@InternalMapConductorApi +internal fun listVersions(list: List): Flow> = + if (list is SnapshotStateList) { + // Wrapped so that each change counts, even one that leaves an equal list: + // a state's equals does not look at its id, so replacing one state with + // another drawn the same way would otherwise go unseen. + snapshotFlow { Version(list.toList()) }.map { it.items } + } else { + flowOf(list) + } + +@InternalMapConductorApi +private class Version( + val items: List, +) diff --git a/src/main/java/com/mapconductor/compose/circle/CircleCompose.kt b/src/main/java/com/mapconductor/compose/circle/CircleCompose.kt index 42fc93f..cc9210d 100644 --- a/src/main/java/com/mapconductor/compose/circle/CircleCompose.kt +++ b/src/main/java/com/mapconductor/compose/circle/CircleCompose.kt @@ -1,5 +1,6 @@ package com.mapconductor.compose.circle +import com.mapconductor.compose.listVersions import com.mapconductor.compose.LocalOverlayTileActivity import com.mapconductor.core.controller.OverlayKind import com.mapconductor.compose.rememberAddProgress @@ -74,34 +75,37 @@ fun MapViewScope.Circles( val tracking = onAddStart != null || onAddProgress != null || onAddEnd != null LaunchedEffect(states) { - val prevIds = prevIdsState.value - val (nextIds, added) = + // Again after each add to a mutableStateListOf: see listVersions. + listVersions(states).collect { list -> + val prevIds = prevIdsState.value + val (nextIds, added) = + withContext(Dispatchers.Default) { + overlayStateIds(list) to progress.newStates(list, prevIds, tracking) + } + prevIdsState.value = nextIds + // Before the hand-over, so that no arrival comes ahead of it. + progress.track(list, nextIds, added) withContext(Dispatchers.Default) { - overlayStateIds(states) to progress.newStates(states, prevIds, tracking) - } - prevIdsState.value = nextIds - // Before the hand-over, so that no arrival comes ahead of it. - progress.track(states, nextIds, added) - withContext(Dispatchers.Default) { - // While this Circles() is the only writer -- the published membership - // is still the list it published last, or there is nothing yet -- its - // list is handed over as it is. Building a map of hundreds of - // thousands of circles took seconds per hand-over, and so did walking it. - val handOver = if (nextIds.size == states.size) OverlayStateList(states.toList()) else null - collector.flow.update { current -> - val alone = current === ownList[0] || (current.isEmpty() && prevIds.isEmpty()) - if (handOver != null && alone) { - handOver - } else { - // Merge only the ids this Circles() owns, so several - // Circles()/Circle() can share one map's collector. - val next = copyOverlayStates(current) - for (id in prevIds) if (id !in nextIds) next.remove(id) - for (state in states) next[state.id] = state - next + // While this Circles() is the only writer -- the published membership + // is still the list it published last, or there is nothing yet -- its + // list is handed over as it is. Building a map of hundreds of + // thousands of circles took seconds per hand-over, and so did walking it. + val handOver = if (nextIds.size == list.size) OverlayStateList(list.toList()) else null + collector.flow.update { current -> + val alone = current === ownList[0] || (current.isEmpty() && prevIds.isEmpty()) + if (handOver != null && alone) { + handOver + } else { + // Merge only the ids this Circles() owns, so several + // Circles()/Circle() can share one map's collector. + val next = copyOverlayStates(current) + for (id in prevIds) if (id !in nextIds) next.remove(id) + for (state in list) next[state.id] = state + next + } } + ownList[0] = handOver?.takeIf { collector.flow.value === it } } - ownList[0] = handOver?.takeIf { collector.flow.value === it } } } diff --git a/src/main/java/com/mapconductor/compose/marker/MarkerCompose.kt b/src/main/java/com/mapconductor/compose/marker/MarkerCompose.kt index 21a0fa7..a76e60a 100644 --- a/src/main/java/com/mapconductor/compose/marker/MarkerCompose.kt +++ b/src/main/java/com/mapconductor/compose/marker/MarkerCompose.kt @@ -1,5 +1,6 @@ package com.mapconductor.compose.marker +import com.mapconductor.compose.listVersions import com.mapconductor.compose.rememberAddProgress import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect @@ -62,35 +63,38 @@ fun MapViewScope.Markers( val tracking = onAddStart != null || onAddProgress != null || onAddEnd != null LaunchedEffect(states) { - val startedAt = SystemClock.elapsedRealtime() - markerTrace("collector effect start count=${states.size}") - val prevIds = prevIdsState.value - val (nextIds, added) = + // Again after each add to a mutableStateListOf: see listVersions. + listVersions(states).collect { list -> + val startedAt = SystemClock.elapsedRealtime() + markerTrace("collector effect start count=${list.size}") + val prevIds = prevIdsState.value + val (nextIds, added) = + withContext(Dispatchers.Default) { + list.asSequence().map { it.id }.toSet() to progress.newStates(list, prevIds, tracking) + } + markerTrace("collector ids created count=${nextIds.size}") + prevIdsState.value = nextIds + // Before the hand-over, so that no arrival comes ahead of it. + progress.track(list, nextIds, added) + // For very large marker sets, avoid per-marker SharedFlow emits which can backpressure and + // block rendering; instead publish the whole map in one StateFlow update. withContext(Dispatchers.Default) { - states.asSequence().map { it.id }.toSet() to progress.newStates(states, prevIds, tracking) - } - markerTrace("collector ids created count=${nextIds.size}") - prevIdsState.value = nextIds - // Before the hand-over, so that no arrival comes ahead of it. - progress.track(states, nextIds, added) - // For very large marker sets, avoid per-marker SharedFlow emits which can backpressure and - // block rendering; instead publish the whole map in one StateFlow update. - withContext(Dispatchers.Default) { - val removedIds = prevIds - nextIds - // Merge only the ids this Markers() owns into the shared collector so - // several Markers()/Marker() can share one map without clobbering each - // other. Assigning the whole map (a full replace) dropped everyone - // else's markers, so the last Markers() to run won and erased the rest. - collector.flow.update { current -> - val next = current.toMutableMap() - for (id in removedIds) next.remove(id) - for (state in states) next[state.id] = state - next + val removedIds = prevIds - nextIds + // Merge only the ids this Markers() owns into the shared collector so + // several Markers()/Marker() can share one map without clobbering each + // other. Assigning the whole map (a full replace) dropped everyone + // else's markers, so the last Markers() to run won and erased the rest. + collector.flow.update { current -> + val next = current.toMutableMap() + for (id in removedIds) next.remove(id) + for (state in list) next[state.id] = state + next + } + markerTrace( + "collector flow assigned count=${list.size} " + + "elapsedMs=${SystemClock.elapsedRealtime() - startedAt}", + ) } - markerTrace( - "collector flow assigned count=${states.size} " + - "elapsedMs=${SystemClock.elapsedRealtime() - startedAt}", - ) } } diff --git a/src/main/java/com/mapconductor/compose/polygon/PolygonComponent.kt b/src/main/java/com/mapconductor/compose/polygon/PolygonComponent.kt index 91a958e..2260421 100644 --- a/src/main/java/com/mapconductor/compose/polygon/PolygonComponent.kt +++ b/src/main/java/com/mapconductor/compose/polygon/PolygonComponent.kt @@ -1,5 +1,6 @@ package com.mapconductor.compose.polygon +import com.mapconductor.compose.listVersions import com.mapconductor.compose.LocalOverlayTileActivity import com.mapconductor.core.controller.OverlayKind import com.mapconductor.compose.rememberAddProgress @@ -72,29 +73,32 @@ fun MapViewScope.Polygons( val tracking = onAddStart != null || onAddProgress != null || onAddEnd != null LaunchedEffect(states) { - val prevIds = prevIdsState.value - val (nextIds, added) = - withContext(Dispatchers.Default) { - // Union the holes once per newly added state, as Polygon(state) does. - for (state in states) { - if (state.id !in prevIds && state.holes.size > 1) { - state.unionHolesInPlace() + // Again after each add to a mutableStateListOf: see listVersions. + listVersions(states).collect { list -> + val prevIds = prevIdsState.value + val (nextIds, added) = + withContext(Dispatchers.Default) { + // Union the holes once per newly added state, as Polygon(state) does. + for (state in list) { + if (state.id !in prevIds && state.holes.size > 1) { + state.unionHolesInPlace() + } } + list.asSequence().map { it.id }.toSet() to progress.newStates(list, prevIds, tracking) + } + prevIdsState.value = nextIds + // Before the hand-over, so that no arrival comes ahead of it. + progress.track(list, nextIds, added) + withContext(Dispatchers.Default) { + val removedIds = prevIds - nextIds + // Merge only the ids this Polygons() owns, so several + // Polygons()/Polygon() can share one map's collector. + collector.flow.update { current -> + val next = current.toMutableMap() + for (id in removedIds) next.remove(id) + for (state in list) next[state.id] = state + next } - states.asSequence().map { it.id }.toSet() to progress.newStates(states, prevIds, tracking) - } - prevIdsState.value = nextIds - // Before the hand-over, so that no arrival comes ahead of it. - progress.track(states, nextIds, added) - withContext(Dispatchers.Default) { - val removedIds = prevIds - nextIds - // Merge only the ids this Polygons() owns, so several - // Polygons()/Polygon() can share one map's collector. - collector.flow.update { current -> - val next = current.toMutableMap() - for (id in removedIds) next.remove(id) - for (state in states) next[state.id] = state - next } } } diff --git a/src/main/java/com/mapconductor/compose/polyline/PolylineComponent.kt b/src/main/java/com/mapconductor/compose/polyline/PolylineComponent.kt index b1265f0..95314cc 100644 --- a/src/main/java/com/mapconductor/compose/polyline/PolylineComponent.kt +++ b/src/main/java/com/mapconductor/compose/polyline/PolylineComponent.kt @@ -1,5 +1,6 @@ package com.mapconductor.compose.polyline +import com.mapconductor.compose.listVersions import com.mapconductor.compose.LocalOverlayTileActivity import com.mapconductor.core.controller.OverlayKind import com.mapconductor.compose.rememberAddProgress @@ -71,23 +72,26 @@ fun MapViewScope.Polylines( val tracking = onAddStart != null || onAddProgress != null || onAddEnd != null LaunchedEffect(states) { - val prevIds = prevIdsState.value - val (nextIds, added) = + // Again after each add to a mutableStateListOf: see listVersions. + listVersions(states).collect { list -> + val prevIds = prevIdsState.value + val (nextIds, added) = + withContext(Dispatchers.Default) { + list.asSequence().map { it.id }.toSet() to progress.newStates(list, prevIds, tracking) + } + prevIdsState.value = nextIds + // Before the hand-over, so that no arrival comes ahead of it. + progress.track(list, nextIds, added) withContext(Dispatchers.Default) { - states.asSequence().map { it.id }.toSet() to progress.newStates(states, prevIds, tracking) - } - prevIdsState.value = nextIds - // Before the hand-over, so that no arrival comes ahead of it. - progress.track(states, nextIds, added) - withContext(Dispatchers.Default) { - val removedIds = prevIds - nextIds - // Merge only the ids this Polylines() owns, so several - // Polylines()/Polyline() can share one map's collector. - collector.flow.update { current -> - val next = current.toMutableMap() - for (id in removedIds) next.remove(id) - for (state in states) next[state.id] = state - next + val removedIds = prevIds - nextIds + // Merge only the ids this Polylines() owns, so several + // Polylines()/Polyline() can share one map's collector. + collector.flow.update { current -> + val next = current.toMutableMap() + for (id in removedIds) next.remove(id) + for (state in list) next[state.id] = state + next + } } } } diff --git a/src/test/java/com/mapconductor/compose/InPlaceListTest.kt b/src/test/java/com/mapconductor/compose/InPlaceListTest.kt new file mode 100644 index 0000000..1f309f5 --- /dev/null +++ b/src/test/java/com/mapconductor/compose/InPlaceListTest.kt @@ -0,0 +1,183 @@ +package com.mapconductor.compose + +import androidx.compose.runtime.AbstractApplier +import androidx.compose.runtime.BroadcastFrameClock +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Composition +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Recomposer +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.snapshots.Snapshot +import com.mapconductor.compose.circle.Circles +import com.mapconductor.compose.circle.LocalCircleCollector +import com.mapconductor.compose.marker.LocalMarkerCollector +import com.mapconductor.compose.marker.Markers +import com.mapconductor.compose.polygon.LocalPolygonCollector +import com.mapconductor.compose.polygon.Polygons +import com.mapconductor.compose.polyline.LocalPolylineCollector +import com.mapconductor.compose.polyline.Polylines +import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polyline.PolylineState +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withContext +import kotlinx.coroutines.yield + +/** + * `Markers` / `Circles` / `Polylines` / `Polygons` に `mutableStateListOf` を渡し、 + * 同じ一覧に足したり消したりしたものが地図の collector まで届く。 + * + * 一覧が差し替わったときにしか渡し直していなかったので、タップのたびに + * `markers.add(…)` するコードはログでは 1 本ずつ増え、地図には 1 本も出なかった。 + */ +@OptIn(ExperimentalCoroutinesApi::class) +class InPlaceListTest { + @Before + fun setUp() = Dispatchers.setMain(Dispatchers.Unconfined) + + @After + fun tearDown() = Dispatchers.resetMain() + + private class NoNodeApplier : AbstractApplier(Unit) { + override fun insertTopDown( + index: Int, + instance: Unit, + ) = Unit + + override fun insertBottomUp( + index: Int, + instance: Unit, + ) = Unit + + override fun remove( + index: Int, + count: Int, + ) = Unit + + override fun move( + from: Int, + to: Int, + count: Int, + ) = Unit + + override fun onClear() = Unit + } + + /** CirclesCollectionTest と同じ: 合成し、各手順のあと落ち着くまで回す。 */ + private fun compose( + content: @Composable () -> Unit, + vararg steps: () -> Unit, + ) = runBlocking { + val clock = BroadcastFrameClock() + withContext(clock + Dispatchers.Unconfined) { + val recomposer = Recomposer(coroutineContext) + val job = + launch(start = CoroutineStart.UNDISPATCHED) { + recomposer.runRecomposeAndApplyChanges() + } + val composition = Composition(NoNodeApplier(), recomposer) + composition.setContent(content) + + suspend fun settle() { + repeat(10) { + Snapshot.sendApplyNotifications() + yield() + clock.sendFrame(0L) + yield() + Thread.sleep(20) + } + } + settle() + for (step in steps) { + step() + settle() + } + composition.dispose() + recomposer.close() + job.join() + } + } + + private fun point(id: String): GeoPoint { + val d = id.hashCode() % 1000 * 1e-5 + return GeoPoint.fromLatLong(35.68 + d, 139.76) + } + + private fun marker(id: String) = MarkerState(position = point(id), id = id) + + private fun circle(id: String) = CircleState(center = point(id), radiusMeters = 10.0, id = id) + + private fun line(id: String) = PolylineState(points = listOf(point(id), point("$id-end")), id = id) + + private fun polygon(id: String) = PolygonState(points = listOf(point(id), point("$id-b"), point("$id-c")), id = id) + + @Test + fun statesAddedToAMutableStateListReachTheMap() { + val scope = MapViewScope() + val markers = mutableStateListOf() + val circles = mutableStateListOf(circle("c1")) + val lines = mutableStateListOf() + val polygons = mutableStateListOf() + val seen = mutableListOf>>() + + fun look() { + seen += + listOf( + scope.markerCollector.flow.value.keys + .toSet(), + scope.circleCollector.flow.value.keys + .toSet(), + scope.polylineCollector.flow.value.keys + .toSet(), + scope.polygonCollector.flow.value.keys + .toSet(), + ) + } + + compose( + { + CompositionLocalProvider( + LocalMarkerCollector provides scope.markerCollector, + LocalCircleCollector provides scope.circleCollector, + LocalPolylineCollector provides scope.polylineCollector, + LocalPolygonCollector provides scope.polygonCollector, + ) { + scope.Markers(markers) + scope.Circles(circles) + scope.Polylines(lines) + scope.Polygons(polygons) + } + }, + { look() }, + // タップ 1 回ぶん: 同じ一覧に足す + { + markers.add(marker("m1")) + circles.add(circle("c2")) + lines.add(line("l1")) + polygons.add(polygon("p1")) + }, + { look() }, + { + markers.add(marker("m2")) + circles.removeAt(0) + }, + { look() }, + ) + + assertEquals(listOf(emptySet(), setOf("c1"), emptySet(), emptySet()), seen[0]) + assertEquals(listOf(setOf("m1"), setOf("c1", "c2"), setOf("l1"), setOf("p1")), seen[1]) + assertEquals(listOf(setOf("m1", "m2"), setOf("c2"), setOf("l1"), setOf("p1")), seen[2]) + } +}