Yokan / rebuild
Course 1 8624561

ProfileStorageLease.wasm.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageLease.wasm.kt

implementation38 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)23package eu.friedcutlet.yokan.app.profiles45import kotlinx.coroutines.NonCancellable6import kotlinx.coroutines.await7import kotlinx.coroutines.withContext8import kotlin.js.JsAny9import kotlin.js.Promise10import eu.friedcutlet.yokan.domain.ProfileId1112internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease {13    if (id == ProfileId.Default) return ProfileStorageLease {}14    var acquired: JsAny? = null15    try {16        withContext(NonCancellable) { acquired = reserveProfile(id.value).await<JsAny>() }17        val handle = checkNotNull(acquired)18        return ProfileStorageLease { withContext(NonCancellable) { releaseProfile(handle).await<JsAny?>() } }19    } catch (error: Throwable) {20        acquired?.let { handle -> withContext(NonCancellable) { releaseProfile(handle).await<JsAny?>() } }21        throw error22    }23}2425private fun reserveProfile(id: String): Promise<JsAny> = js(26    """new Promise((resolve, reject) => {27        if (!navigator.locks || !navigator.locks.request) {28            reject(new Error('Profile storage requires Web Locks')); return;29        }30        const handle = { release: null, done: null };31        handle.done = navigator.locks.request('yokan-profile-storage:' + id, {ifAvailable: true}, lock => {32            if (!lock) throw new Error('Profile is open in another tab');33            return new Promise(release => { handle.release = release; resolve(handle); });34        });35        handle.done.catch(reject);36    })""",37)38private fun releaseProfile(handle: JsAny): Promise<JsAny?> = js("(handle.release(), handle.done)")39

Search chapters, reference and source filenames.