Implementing a custom property delegate that provides lifecycle-aware values
Often, we need to declare a class property, which should depend on the lifecycle state of Activity
or Fragment
. In this recipe, we are going to employ both the Kotlin Lazy
delegate and the Lifecycle
class provided by the Android Architecture Components library (https://developer.android.com/topic/libraries/architecture/). We are going to implement a custom property delegate that will provide values in a lazy manner. This means that they are going to be instantiated only on the first call. Moreover, we are going to clear their values once Activity
or Fragment
gets destroyed. This will avoid memory leaks, which can be caused by managing properties dependent on the Context
instance with the standard Lazy
delegate.
Getting ready
The basic Lazy
delegate initialized using the lazy()
function provided by the standard library gives the desired possibility of declaring a property of a non-null type, which can only be instantiated...