package eu.friedcutlet.yokan.app.profiles import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import kotlinx.coroutines.yield /** Composition disposal captures final progress before the navigator begins awaited retirement. */ internal class ProfileUiLifetime { private val lock = PlatformLock() private val mounts = mutableMapOf>>() fun mount(session: ProfileSession): () -> Unit { val ticket = CompletableDeferred() lock.withLock { mounts.getOrPut(session) { mutableSetOf() }.add(ticket) } return { lock.withLock { mounts[session]?.let { it.remove(ticket); if (it.isEmpty()) mounts.remove(session) } ticket.complete(Unit) } } } suspend fun detach(session: ProfileSession) = withTimeout(15_000) { val tickets = lock.withLock { mounts[session]?.toList().orEmpty() } withContext(Dispatchers.Main) { tickets.forEach { it.await() } // Resume after the synchronous apply/disposal pass, including child disposers. yield() } } }