Add delegates that allows to lazily initialize value on certain lifecycle event

This commit is contained in:
Kirill Nayduik 2022-01-17 17:55:27 +03:00
parent cde08fa3f0
commit 3476324b84
2 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,37 @@
package ru.touchin.lifecycle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import java.lang.IllegalStateException
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Delegate that allows to lazily initialize value on certain lifecycle event
* @param initializeEvent is event when value should be initialize
* @param initializer callback that handles value initialization
*/
class OnLifecycle<R : LifecycleOwner, T>(
private val lifecycleOwner: R,
private val initializeEvent: Lifecycle.Event,
private val initializer: (R) -> T
) : ReadOnlyProperty<R, T> {
private var value: T? = null
init {
lifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (initializeEvent == event && value == null) {
value = initializer.invoke(lifecycleOwner)
}
}
})
}
override fun getValue(thisRef: R, property: KProperty<*>) = value
?: throw IllegalStateException("Can't get access to value before $initializeEvent. Current is ${thisRef.lifecycle.currentState}")
}

View File

@ -0,0 +1,31 @@
package ru.touchin.lifecycle.extensions
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import ru.touchin.lifecycle.OnLifecycle
import kotlin.properties.ReadOnlyProperty
fun <R : LifecycleOwner, T> R.onCreateEvent(
initializer: (R) -> T
): ReadOnlyProperty<R, T> {
return OnLifecycle(this, Lifecycle.Event.ON_CREATE, initializer)
}
fun <R : LifecycleOwner, T> R.onStartEvent(
initializer: (R) -> T
): ReadOnlyProperty<R, T> {
return OnLifecycle(this, Lifecycle.Event.ON_START, initializer)
}
fun <R : LifecycleOwner, T> R.onResumeEvent(
initializer: (R) -> T
): ReadOnlyProperty<R, T> {
return OnLifecycle(this, Lifecycle.Event.ON_RESUME, initializer)
}
fun <R : LifecycleOwner, T> R.onLifecycle(
initializeEvent: Lifecycle.Event,
initializer: (R) -> T
): ReadOnlyProperty<R, T> {
return OnLifecycle(this, initializeEvent, initializer)
}