ProfileUiLifetime.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileUiLifetime.kt
1package eu.friedcutlet.yokan.app.profiles23import eu.friedcutlet.yokan.util.PlatformLock4import kotlinx.coroutines.CompletableDeferred5import kotlinx.coroutines.Dispatchers6import kotlinx.coroutines.withContext7import kotlinx.coroutines.withTimeout8import kotlinx.coroutines.yield910/** Composition disposal captures final progress before the navigator begins awaited retirement. */11internal class ProfileUiLifetime {12 private val lock = PlatformLock()13 private val mounts = mutableMapOf<ProfileSession, MutableSet<CompletableDeferred<Unit>>>()14 fun mount(session: ProfileSession): () -> Unit {15 val ticket = CompletableDeferred<Unit>()16 lock.withLock { mounts.getOrPut(session) { mutableSetOf() }.add(ticket) }17 return {18 lock.withLock {19 mounts[session]?.let { it.remove(ticket); if (it.isEmpty()) mounts.remove(session) }20 ticket.complete(Unit)21 }22 }23 }24 suspend fun detach(session: ProfileSession) = withTimeout(15_000) {25 val tickets = lock.withLock { mounts[session]?.toList().orEmpty() }26 withContext(Dispatchers.Main) {27 tickets.forEach { it.await() }28 // Resume after the synchronous apply/disposal pass, including child disposers.29 yield()30 }31 }32}33