From 26bae387a16ed5370c2b7673545a4746c35f9794 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Fri, 20 Nov 2026 19:47:09 -0800 Subject: [PATCH 1/3] Tell which states left a bulk list by a pass token, not id lookups listenToWrittenStates looked every id of the new map up in the old one and every id of the old map up in the new one: about 1.7 s on the main thread for the 576k/724k circles of the antenna sample on a Pixel 5a. The collector now listens through a PassToken replaced at every pass. A state in the new map is moved to the current token; a state of the old map still on an older token of this collector was not in the new one, and stops. One read per state, no lookups; an id is still looked up for a state not yet listening here, to stop what held that id before. The pass is now 1.2-1.3 s. Of that, merely iterating the PersistentOrderedMapBuilder is about 0.44 s per 576k entries (it looks the next key up at each step), which only a different hand-over can avoid. --- .../com/mapconductor/core/OverlayCollector.kt | 44 ++++++++++++++----- .../mapconductor/core/StateMutationSignal.kt | 4 +- .../core/OverlayCollectorMutationTest.kt | 24 ++++++++++ 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/mapconductor/core/OverlayCollector.kt b/src/main/java/com/mapconductor/core/OverlayCollector.kt index 627c426..378653c 100644 --- a/src/main/java/com/mapconductor/core/OverlayCollector.kt +++ b/src/main/java/com/mapconductor/core/OverlayCollector.kt @@ -78,8 +78,7 @@ interface OverlayCollectorInterface { class OverlayCollector( private val updateDebounce: Duration, scope: CoroutineScope = CoroutineScope(Dispatchers.Main.immediate), -) : OverlayCollectorInterface, - StateMutationListener { +) : OverlayCollectorInterface { private val scope = scope private val addSharedFlow = MutableSharedFlow(1000) private val removeSharedFlow = MutableSharedFlow(1000) @@ -112,6 +111,25 @@ class OverlayCollector( /** The membership [listenToWrittenStates] last listened to. */ @Volatile private var published: Map = emptyMap() + /** + * What this collector listens through, replaced at every + * [listenToWrittenStates] pass. A state's listener says whether it reports + * here (a [PassToken] of this collector) and whether this pass has seen it + * (the current one): telling which states left a bulk list takes one read + * per state, not a lookup of each id in the other map. + */ + @Volatile private var token = PassToken(this) + + @InternalMapConductorApi + private class PassToken( + val collector: OverlayCollector<*>, + ) : StateMutationListener { + override fun onMutated(state: ComponentState) = collector.onMutated(state) + } + + private fun tokenOf(state: T): PassToken? = + (state.mutations.currentListener as? PassToken)?.takeIf { it.collector === this } + init { scope.launch { addSharedFlow.debounceBatch(5.milliseconds, 100).collect { states -> @@ -147,6 +165,8 @@ class OverlayCollector( private fun listenToWrittenStates(states: Map) { val previous = published published = states + val pass = PassToken(this) + token = pass val anyPending = pendingAdds.isNotEmpty() for ((id, state) in states) { if (anyPending) { @@ -155,15 +175,19 @@ class OverlayCollector( } // Already reporting here: whatever held its id before was stopped // when it started. Most of a bulk list is, from the last pass. - if (state.mutations.isListenedBy(this)) continue - val old = previous[id] - if (old !== null && old !== state) stop(old) - listen(state) + if (tokenOf(state) == null) { + val old = previous[id] + if (old !== null && old !== state) stop(old) + } + state.mutations.listen(pass, state) } + // What the last pass listened to and this one did not see has left. // Only stop what this path started: a state added through [add] may not // have reached [flow] yet (membership is debounced). + val stillPending = pendingAdds.isNotEmpty() for ((id, state) in previous) { - if (id !in states && pendingAdds[id] !== state) stop(state) + val heard = tokenOf(state) ?: continue + if (heard !== pass && (!stillPending || pendingAdds[id] !== state)) state.mutations.stopListening(heard) } } @@ -181,11 +205,11 @@ class OverlayCollector( } private fun listen(state: T) { - state.mutations.listen(this, state) + state.mutations.listen(token, state) } private fun stop(state: T) { - state.mutations.stopListening(this) + tokenOf(state)?.let { state.mutations.stopListening(it) } } /** @@ -194,7 +218,7 @@ class OverlayCollector( * state left listening by a membership change this collector never saw * (a [flow] value replaced before it was collected) is dropped here. */ - override fun onMutated(state: ComponentState) { + private fun onMutated(state: ComponentState) { val channel = mutated ?: return val id = state.id if (pendingAdds[id] !== state && flow.value[id] !== state && published[id] !== state) return diff --git a/src/main/java/com/mapconductor/core/StateMutationSignal.kt b/src/main/java/com/mapconductor/core/StateMutationSignal.kt index 7deb718..af78e80 100644 --- a/src/main/java/com/mapconductor/core/StateMutationSignal.kt +++ b/src/main/java/com/mapconductor/core/StateMutationSignal.kt @@ -54,8 +54,8 @@ class StateMutationSignal { this.listener = listener } - /** Whether writes are reported to [listener]. */ - internal fun isListenedBy(listener: StateMutationListener): Boolean = this.listener === listener + /** Who writes are reported to now: a `() -> Unit`, a [StateMutationListener], or null. */ + internal val currentListener: Any? get() = listener /** Stops reporting, but only if [listener] is the one reported to. */ internal fun stopListening(listener: StateMutationListener) { diff --git a/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt index 08f4f40..82dc31f 100644 --- a/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt +++ b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt @@ -73,6 +73,30 @@ class OverlayCollectorMutationTest { assertEquals(setOf("single", "bulk"), collector.flow.value.keys) } + @Test + fun aBulkListThatDropsAndRestoresSomeStatesKeepsTheRestReporting() = runTest { + val collector = collector(StandardTestDispatcher(testScheduler)) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add("${it.id}=${it.label}") } + val states = List(5) { Thing("s$it", "0") } + fun publish(list: List) { + collector.flow.value = copyOverlayStates(list.associateBy { it.id }) + } + publish(states) + advanceUntilIdle() + publish(states.filterIndexed { index, _ -> index % 2 == 0 }) + advanceUntilIdle() + states.forEach { it.label = "1" } + advanceUntilIdle() + assertEquals(listOf("s0=1", "s2=1", "s4=1"), seen.sorted()) + seen.clear() + publish(states) + advanceUntilIdle() + states.forEach { it.label = "2" } + advanceUntilIdle() + assertEquals(states.map { "${it.id}=2" }, seen.sorted()) + } + private fun collector(dispatcher: TestDispatcher) = OverlayCollector( updateDebounce = window, From 17ad72db9fc9fbb76e3acdc317bd0cb43ab9f8f6 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Fri, 20 Nov 2026 20:00:15 -0800 Subject: [PATCH 2/3] Let a collection hand its list over as the collector's membership A collector's membership is a MutableMap, and for a bulk collection that map was a PersistentOrderedMap of every state: building it took about 1.8 s per hand-over for the antenna sample's 576k circles on a Pixel 5a, and merely iterating it about 0.44 s per pass (it looks the next key up at each step), on the collector's pass and the overlay's toList. OverlayStateList is a MutableMap over the list a collection was given: iterating it walks the list, and only a key lookup builds an index. The collector's listener pass and CircleOverlay walk the list; the overlay hands the list itself to the controller, and the added-tracker gets the ids lazily. A write from the latest pass's token is known to be from a member without a lookup. A published map is still not to be written to; one that is follows its index. The ids must be distinct (the compose Circles hands a list over only when they are). --- .../com/mapconductor/core/OverlayCollector.kt | 34 ++++++++-- .../com/mapconductor/core/OverlayStateMaps.kt | 67 +++++++++++++++++++ .../mapconductor/core/circle/CircleOverlay.kt | 7 +- .../core/OverlayCollectorMutationTest.kt | 26 +++++++ 4 files changed, 125 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/mapconductor/core/OverlayCollector.kt b/src/main/java/com/mapconductor/core/OverlayCollector.kt index 378653c..2571453 100644 --- a/src/main/java/com/mapconductor/core/OverlayCollector.kt +++ b/src/main/java/com/mapconductor/core/OverlayCollector.kt @@ -124,7 +124,20 @@ class OverlayCollector( private class PassToken( val collector: OverlayCollector<*>, ) : StateMutationListener { - override fun onMutated(state: ComponentState) = collector.onMutated(state) + override fun onMutated(state: ComponentState) = collector.onMutated(state, this) + } + + /** Each state of [states] with its id, walking an [OverlayStateList]'s list rather than its index. */ + private inline fun forEachState( + states: Map, + action: (id: String, state: T) -> Unit, + ) { + if (states is OverlayStateList<*>) { + @Suppress("UNCHECKED_CAST") + (states as OverlayStateList).forEachState { action(it.id, it) } + } else { + for ((id, state) in states) action(id, state) + } } private fun tokenOf(state: T): PassToken? = @@ -168,7 +181,7 @@ class OverlayCollector( val pass = PassToken(this) token = pass val anyPending = pendingAdds.isNotEmpty() - for ((id, state) in states) { + forEachState(states) { id, state -> if (anyPending) { val pending = pendingAdds.remove(id) if (pending !== null && pending !== state) stop(pending) @@ -185,9 +198,11 @@ class OverlayCollector( // Only stop what this path started: a state added through [add] may not // have reached [flow] yet (membership is debounced). val stillPending = pendingAdds.isNotEmpty() - for ((id, state) in previous) { - val heard = tokenOf(state) ?: continue - if (heard !== pass && (!stillPending || pendingAdds[id] !== state)) state.mutations.stopListening(heard) + forEachState(previous) { id, state -> + val heard = tokenOf(state) + if (heard != null && heard !== pass && (!stillPending || pendingAdds[id] !== state)) { + state.mutations.stopListening(heard) + } } } @@ -218,10 +233,15 @@ class OverlayCollector( * state left listening by a membership change this collector never saw * (a [flow] value replaced before it was collected) is dropped here. */ - private fun onMutated(state: ComponentState) { + private fun onMutated( + state: ComponentState, + via: PassToken, + ) { val channel = mutated ?: return val id = state.id - if (pendingAdds[id] !== state && flow.value[id] !== state && published[id] !== state) return + // Heard through the latest pass's token: the latest published membership + // has it. Otherwise look it up (pending adds, a newer flow value). + if (via !== token && pendingAdds[id] !== state && flow.value[id] !== state && published[id] !== state) return @Suppress("UNCHECKED_CAST") channel.trySend(state as T) } diff --git a/src/main/java/com/mapconductor/core/OverlayStateMaps.kt b/src/main/java/com/mapconductor/core/OverlayStateMaps.kt index c38e4bb..b5f6853 100644 --- a/src/main/java/com/mapconductor/core/OverlayStateMaps.kt +++ b/src/main/java/com/mapconductor/core/OverlayStateMaps.kt @@ -18,3 +18,70 @@ fun overlayStateIds(states: Iterable): Set = persistentHashSetOf().builder().apply { for (state in states) add(state.id) }.build() + +/** + * A collector's membership handed over as the list a collection was given, + * for collections of hundreds of thousands of states: building and walking a + * map of them cost seconds per hand-over, and the readers that matter (the + * collector and the overlays) only walk the states in order. + * + * [states] is the list itself. Looking a key up builds an index on first use. + * Like every published generation it is not to be written to; a write goes to + * the index and [states] then follows the index. + * + * The ids in [list] must be distinct: [states] and [forEachState] do not + * deduplicate. + */ +@InternalMapConductorApi +class OverlayStateList( + private val list: List, +) : AbstractMutableMap() { + @Volatile private var index: LinkedHashMap? = null + + @Volatile private var written = false + + private fun index(): LinkedHashMap = + index ?: synchronized(this) { + index ?: LinkedHashMap((list.size / 0.75f).toInt() + 1).also { map -> + for (state in list) map[state.id] = state + index = map + } + } + + /** The states in order: the list handed over, unless this map was written to. */ + fun states(): List = if (written) ArrayList(index().values) else list + + /** Calls [action] for each state in order, without building the index. */ + inline fun forEachState(action: (T) -> Unit) { + for (state in states()) action(state) + } + + /** The ids, through the index. */ + val ids: Set get() = index().keys + + override val size: Int get() = if (written) index().size else list.size + + override val entries: MutableSet> get() = index().entries + + override fun get(key: String): T? = index()[key] + + override fun containsKey(key: String): Boolean = index().containsKey(key) + + override fun put( + key: String, + value: T, + ): T? { + written = true + return index().put(key, value) + } + + override fun remove(key: String): T? { + written = true + return index().remove(key) + } + + override fun clear() { + written = true + index().clear() + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt b/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt index d76fb87..274c4a8 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt @@ -1,6 +1,7 @@ package com.mapconductor.core.circle import com.mapconductor.core.OverlayAddedTracker +import com.mapconductor.core.OverlayStateList import com.mapconductor.core.controller.BaseMapViewController import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface @@ -29,8 +30,10 @@ class CircleOverlay tilingOptions?.value?.let { options -> (controller as? BaseMapViewController)?.circleTilers()?.forEach { it.options = options } } - val states = data.values.toList() + @Suppress("UNCHECKED_CAST") + val list = data as? OverlayStateList + val states = list?.states() ?: data.values.toList() capable.compositionCircles(states) - added.synced(controller, states, capable::hasCircle, sourceIds = data.keys) + added.synced(controller, states, capable::hasCircle, sourceIds = list?.ids ?: data.keys) } } diff --git a/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt index 82dc31f..0099694 100644 --- a/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt +++ b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt @@ -97,6 +97,32 @@ class OverlayCollectorMutationTest { assertEquals(states.map { "${it.id}=2" }, seen.sorted()) } + @Test + fun aListHandOverReportsWritesOfItsStatesOnly() = runTest { + val collector = collector(StandardTestDispatcher(testScheduler)) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add("${it.id}=${it.label}") } + val states = List(4) { Thing("l$it", "0") } + collector.flow.value = OverlayStateList(states) + advanceUntilIdle() + collector.flow.value = OverlayStateList(states.take(2)) + advanceUntilIdle() + states.forEach { it.label = "1" } + advanceUntilIdle() + assertEquals(listOf("l0=1", "l1=1"), seen.sorted()) + } + + @Test + fun aWrittenListFollowsItsIndex() { + val states = List(3) { Thing("w$it", "0") } + val list = OverlayStateList(states) + assertEquals(states, list.states()) + assertEquals(states[1], list["w1"]) + list.remove("w1") + assertEquals(listOf(states[0], states[2]), list.states()) + assertEquals(setOf("w0", "w2"), list.keys) + } + private fun collector(dispatcher: TestDispatcher) = OverlayCollector( updateDebounce = window, From cdc897a1499205f36da71476acbaed89a27f85b7 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Fri, 20 Nov 2026 21:39:50 -0800 Subject: [PATCH 3/3] Report when a tiler takes a list or draws tiles Adds TileActivity, counted across the tile threads: ShapeTileRenderer is busy while it draws a tile, and ShapeTiler adds its route. Circle, polyline and polygon tilers expose it internally, and BaseMapViewController.overlayTileActivity(kind) (@InternalMapConductorApi) lists a map's tilers of one kind, for the compose collections' onAddStart / onAddEnd to wait for the tiles. --- .../mapconductor/core/circle/CircleTiler.kt | 4 ++ .../core/controller/BaseMapViewController.kt | 6 +++ .../core/controller/OverlayTileActivity.kt | 18 +++++++++ .../mapconductor/core/polygon/PolygonTiler.kt | 8 +++- .../core/polyline/PolylineTiler.kt | 4 ++ .../core/shapetile/ShapeTileRenderer.kt | 8 ++++ .../core/shapetile/ShapeTileSet.kt | 3 ++ .../mapconductor/core/shapetile/ShapeTiler.kt | 9 +++++ .../core/shapetile/TileActivity.kt | 40 +++++++++++++++++++ 9 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/mapconductor/core/controller/OverlayTileActivity.kt create mode 100644 src/main/java/com/mapconductor/core/shapetile/TileActivity.kt diff --git a/src/main/java/com/mapconductor/core/circle/CircleTiler.kt b/src/main/java/com/mapconductor/core/circle/CircleTiler.kt index 9342581..32fce9d 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleTiler.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleTiler.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.circle +import kotlinx.coroutines.flow.StateFlow import com.mapconductor.core.normalizeLng import com.mapconductor.core.raster.RasterLayerSource import com.mapconductor.core.raster.RasterLayerState @@ -68,6 +69,9 @@ class CircleTiler( onTemplate = { template, tileSize -> onTemplate?.invoke(template, tileSize) }, ) + /** Busy while this tiler takes a list or its tiles are drawn. See [com.mapconductor.core.controller.overlayTileActivity]. */ + internal val activity: StateFlow get() = tileSet.shapes.activity.active + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ suspend fun route(data: List): Set = tiler.route(data) diff --git a/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt b/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt index 7ff3bd3..4cbd7ab 100644 --- a/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt +++ b/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt @@ -1,5 +1,7 @@ package com.mapconductor.core.controller +import com.mapconductor.core.polygon.PolygonTiler +import com.mapconductor.core.polygon.PolygonController import com.mapconductor.core.OnCameraMoveHandler import com.mapconductor.core.OnMapEventHandler import com.mapconductor.core.OnMapInitializedHandler @@ -306,6 +308,10 @@ abstract class BaseMapViewController : internal fun circleTilers(): List = overlayControllersOf(OverlayKind.Circle).mapNotNull { (it as? CircleController<*>)?.tiler } + /** The tilers of this map's polygon controllers. */ + internal fun polygonTilers(): List = + overlayControllersOf(OverlayKind.Polygon).mapNotNull { (it as? PolygonController<*>)?.tiler } + /** The tilers of this map's polyline controllers, for [com.mapconductor.core.polyline.PolylineOverlay]'s per-map options. */ internal fun polylineTilers(): List = overlayControllersOf(OverlayKind.Polyline).mapNotNull { (it as? PolylineController<*>)?.tiler } diff --git a/src/main/java/com/mapconductor/core/controller/OverlayTileActivity.kt b/src/main/java/com/mapconductor/core/controller/OverlayTileActivity.kt new file mode 100644 index 0000000..670dbcf --- /dev/null +++ b/src/main/java/com/mapconductor/core/controller/OverlayTileActivity.kt @@ -0,0 +1,18 @@ +package com.mapconductor.core.controller + +import com.mapconductor.core.InternalMapConductorApi +import kotlinx.coroutines.flow.StateFlow + +/** + * Whether each tiler of [kind] on this map is busy -- taking a list or drawing + * tiles -- for the collections' onAddStart / onAddEnd. Empty for a kind without + * tiles. + */ +@InternalMapConductorApi +fun BaseMapViewController.overlayTileActivity(kind: OverlayKind): List> = + when (kind) { + OverlayKind.Circle -> circleTilers().map { it.activity } + OverlayKind.Polyline -> polylineTilers().map { it.activity } + OverlayKind.Polygon -> polygonTilers().map { it.activity } + else -> emptyList() + } diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt index ef060e8..935c565 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.polygon +import kotlinx.coroutines.flow.StateFlow import com.mapconductor.core.raster.RasterLayerSource import com.mapconductor.core.raster.RasterLayerState import com.mapconductor.core.shapetile.ShapeTiler @@ -42,9 +43,11 @@ class PolygonTiler( ) { var onTemplate: (suspend (template: String?, tileSize: Int) -> Unit)? = null + private val tileSet = PolygonTileSet() + private val tiler = ShapeTiler( - tileSet = PolygonTileSet().shapes, + tileSet = tileSet.shapes, canTile = PolygonTileSet::canTile, vertexCount = PolygonTileSet::vertexCount, shouldUseTiles = { count, vertices -> options.shouldUseTiles(count, vertices) }, @@ -52,6 +55,9 @@ class PolygonTiler( onTemplate = { template, tileSize -> onTemplate?.invoke(template, tileSize) }, ) + /** Busy while this tiler takes a list or its tiles are drawn. See [com.mapconductor.core.controller.overlayTileActivity]. */ + internal val activity: StateFlow get() = tileSet.shapes.activity.active + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ suspend fun route(data: List): Set = tiler.route(data) diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineTiler.kt b/src/main/java/com/mapconductor/core/polyline/PolylineTiler.kt index 3f289c6..0811ddb 100644 --- a/src/main/java/com/mapconductor/core/polyline/PolylineTiler.kt +++ b/src/main/java/com/mapconductor/core/polyline/PolylineTiler.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.polyline +import kotlinx.coroutines.flow.StateFlow import com.mapconductor.core.raster.RasterLayerSource import com.mapconductor.core.raster.RasterLayerState import com.mapconductor.core.shapetile.ShapeTiler @@ -59,6 +60,9 @@ class PolylineTiler( onTemplate = { template, tileSize -> onTemplate?.invoke(template, tileSize) }, ) + /** Busy while this tiler takes a list or its tiles are drawn. See [com.mapconductor.core.controller.overlayTileActivity]. */ + internal val activity: StateFlow get() = tileSet.shapes.activity.active + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ suspend fun route(data: List): Set = tiler.route(data) diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt index a7daeb4..565b415 100644 --- a/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt @@ -341,11 +341,19 @@ internal class ShapeTileRenderer( } } + /** Busy while a tile is being drawn; the owning tiler adds its own work. */ + val activity = TileActivity() + override fun renderTile(request: TileRequest): ByteArray? = renderTile(request) { false } override fun renderTile( request: TileRequest, isCancelled: () -> Boolean, + ): ByteArray? = activity.during { drawTile(request, isCancelled) } + + private fun drawTile( + request: TileRequest, + isCancelled: () -> Boolean, ): ByteArray? { val generationAtStart = generation.get() val m = acquireModel() ?: return null diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt index 88327c6..257e1af 100644 --- a/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt @@ -56,6 +56,9 @@ internal class ShapeTileSet( val tileSize: Int get() = renderer.tileSize + /** Busy while tiles of this set are drawn, and while [ShapeTiler] hands it a list. */ + val activity: TileActivity get() = renderer.activity + private val lock = Any() // Never changed once assigned, so the sets [ids] hands out stay as they were. // An ObjectIntMap rather than a HashMap: no node or boxed Int diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt index 2f8e525..748efad 100644 --- a/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt @@ -33,6 +33,15 @@ internal class ShapeTiler( /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ suspend fun route(data: List): Set { + tileSet.activity.begin() + try { + return routeWork(data) + } finally { + tileSet.activity.end() + } + } + + private suspend fun routeWork(data: List): Set { // A city of shapes is a second of work; none of it belongs on the map's thread. val (tileable, useTiles) = withContext(Dispatchers.Default) { diff --git a/src/main/java/com/mapconductor/core/shapetile/TileActivity.kt b/src/main/java/com/mapconductor/core/shapetile/TileActivity.kt new file mode 100644 index 0000000..5f12bea --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/TileActivity.kt @@ -0,0 +1,40 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** + * Whether a tiler is busy: taking a list (`route`) or drawing tiles for the + * map. The collections' onAddStart / onAddEnd read it, so that an app can show + * that the map is still drawing after a filter change or a camera move. + * + * Counted, since tiles are drawn on several threads at once. + */ +@InternalMapConductorApi +class TileActivity { + private var count = 0 + private val busy = MutableStateFlow(false) + + val active: StateFlow = busy.asStateFlow() + + fun begin() = + synchronized(this) { + if (++count == 1) busy.value = true + } + + fun end() = + synchronized(this) { + if (--count == 0) busy.value = false + } + + inline fun during(block: () -> R): R { + begin() + try { + return block() + } finally { + end() + } + } +}