From f791cc6f9cff3a4f98d2c792d64ce126a939f013 Mon Sep 17 00:00:00 2001 From: Koitharu Date: Sat, 9 Sep 2023 16:36:13 +0300 Subject: [PATCH] Added SoftSuspendLazy class --- .../kotatsu/parsers/util/SoftSuspendLazy.kt | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/kotlin/org/koitharu/kotatsu/parsers/util/SoftSuspendLazy.kt diff --git a/src/main/kotlin/org/koitharu/kotatsu/parsers/util/SoftSuspendLazy.kt b/src/main/kotlin/org/koitharu/kotatsu/parsers/util/SoftSuspendLazy.kt new file mode 100644 index 00000000..0a460a0b --- /dev/null +++ b/src/main/kotlin/org/koitharu/kotatsu/parsers/util/SoftSuspendLazy.kt @@ -0,0 +1,33 @@ +package org.koitharu.kotatsu.parsers.util + +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.lang.ref.SoftReference + +/** + * Like a [SuspendLazy] but with [SoftReference] under the hood + */ +class SoftSuspendLazy( + private val initializer: suspend () -> T, +) { + + private val mutex = Mutex() + private var cachedValue: SoftReference? = null + + suspend fun get(): T { + // fast way + cachedValue?.get()?.let { + return it + } + return mutex.withLock { + cachedValue?.get()?.let { + return it + } + val result = initializer() + cachedValue = SoftReference(result) + result + } + } + + suspend fun tryGet() = runCatchingCancellable { get() } +}