ViewModelFinalizer.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/ViewModelFinalizer.kt
1package eu.friedcutlet.yokan.ui.navigation23import kotlinx.coroutines.*4import kotlinx.coroutines.sync.Mutex5import kotlinx.coroutines.sync.withLock67/** Native/file cleanup follows all ViewModel work, including blocking cancellation finalizers. */8internal class ViewModelFinalizer(9 private val work: Job,10 private val dispatcher: CoroutineDispatcher = Dispatchers.Default,11 private val release: suspend () -> Unit,12) {13 private val owner = SupervisorJob()14 private val requested = CompletableDeferred<Unit>()15 private val mutex = Mutex()16 private var released = false17 private val cleanup = CoroutineScope(owner + dispatcher).async(start = CoroutineStart.UNDISPATCHED) {18 requested.await()19 work.join()20 releaseOnce()21 }22 fun retire() { work.cancel(); requested.complete(Unit) }23 suspend fun closeAndJoin() = withContext(NonCancellable) {24 retire()25 cleanup.join()26 releaseOnce()27 owner.join()28 }29 private suspend fun releaseOnce() = withContext(dispatcher + NonCancellable) {30 mutex.withLock {31 if (!released) {32 release()33 released = true34 owner.complete()35 }36 }37 }38}39