LibreTube/app/src/main/java/com/github/libretube/api/ResettableLazy.kt

57 lines
1.3 KiB
Kotlin
Raw Normal View History

2022-08-27 18:43:24 +05:30
package com.github.libretube.api
2022-02-09 23:40:39 +05:30
2022-06-03 00:40:16 +05:30
import java.util.*
2022-02-09 23:40:39 +05:30
import kotlin.reflect.KProperty
class ResettableLazyManager {
// we synchronize to make sure the timing of a reset() call and new inits do not collide
2022-07-02 21:53:24 +05:30
private val managedDelegates = LinkedList<Resettable>()
2022-02-09 23:40:39 +05:30
fun register(managed: Resettable) {
2022-05-20 03:52:10 +05:30
synchronized(managedDelegates) {
2022-02-09 23:40:39 +05:30
managedDelegates.add(managed)
}
}
fun reset() {
2022-05-20 03:52:10 +05:30
synchronized(managedDelegates) {
2022-02-09 23:40:39 +05:30
managedDelegates.forEach { it.reset() }
managedDelegates.clear()
}
}
}
interface Resettable {
fun reset()
}
2022-05-21 13:32:04 +05:30
class ResettableLazy<PROPTYPE>(val manager: ResettableLazyManager, val init: () -> PROPTYPE) :
Resettable {
@Volatile
var lazyHolder = makeInitBlock()
2022-02-09 23:40:39 +05:30
operator fun getValue(thisRef: Any?, property: KProperty<*>): PROPTYPE {
return lazyHolder.value
}
override fun reset() {
lazyHolder = makeInitBlock()
}
2022-07-02 21:53:24 +05:30
private fun makeInitBlock(): Lazy<PROPTYPE> {
2022-02-09 23:40:39 +05:30
return lazy {
manager.register(this)
init()
}
}
}
fun <PROPTYPE> resettableLazy(
manager: ResettableLazyManager,
init: () -> PROPTYPE
): ResettableLazy<PROPTYPE> {
2022-02-09 23:40:39 +05:30
return ResettableLazy(manager, init)
}
2022-05-20 03:52:10 +05:30
fun resettableManager(): ResettableLazyManager = ResettableLazyManager()