Added SoftSuspendLazy class

pull/252/head
Koitharu 3 years ago
parent aae3fa3b05
commit f791cc6f9c
Signed by: Koitharu
GPG Key ID: 676DEE768C17A9D7

@ -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<T : Any>(
private val initializer: suspend () -> T,
) {
private val mutex = Mutex()
private var cachedValue: SoftReference<T>? = 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() }
}
Loading…
Cancel
Save