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

52 lines
1.3 KiB
Kotlin
Raw Normal View History

2022-02-09 23:40:39 +05:30
package com.github.libretube
import java.util.*
import kotlin.reflect.KProperty
class ResettableLazyManager {
// we synchronize to make sure the timing of a reset() call and new inits do not collide
val managedDelegates = LinkedList<Resettable>()
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-20 03:52:10 +05:30
class ResettableLazy<PROPTYPE>(val manager: ResettableLazyManager, val init: () -> PROPTYPE) : Resettable {
2022-02-09 23:40:39 +05:30
@Volatile var lazyHolder = makeInitBlock()
operator fun getValue(thisRef: Any?, property: KProperty<*>): PROPTYPE {
return lazyHolder.value
}
override fun reset() {
lazyHolder = makeInitBlock()
}
fun makeInitBlock(): Lazy<PROPTYPE> {
return lazy {
manager.register(this)
init()
}
}
}
2022-05-20 03:52:10 +05:30
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()