package eu.friedcutlet.yokan.ui.navigation import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** Native/file cleanup follows all ViewModel work, including blocking cancellation finalizers. */ internal class ViewModelFinalizer( private val work: Job, private val dispatcher: CoroutineDispatcher = Dispatchers.Default, private val release: suspend () -> Unit, ) { private val owner = SupervisorJob() private val requested = CompletableDeferred() private val mutex = Mutex() private var released = false private val cleanup = CoroutineScope(owner + dispatcher).async(start = CoroutineStart.UNDISPATCHED) { requested.await() work.join() releaseOnce() } fun retire() { work.cancel(); requested.complete(Unit) } suspend fun closeAndJoin() = withContext(NonCancellable) { retire() cleanup.join() releaseOnce() owner.join() } private suspend fun releaseOnce() = withContext(dispatcher + NonCancellable) { mutex.withLock { if (!released) { release() released = true owner.complete() } } } }