Lazybones
A super lazy and fluent Kotlin expression for initializing lifecycle-aware property.
Including in your project
Gradle
Add below codes to your root build.gradle
file (not your module build.gradle file).
And add a dependency code to your module's build.gradle
file.
Usage
lifecycleAware
We can initialize a lifecycle-aware object lazily using the lifecycleAware
keyword.
The lifecycleAware
functionality can be used to register & unregister listeners, clear something,
show & dismiss and dispose of disposable objects as lifecycle changes by lifecycle owner(Activity, Fragment).
If we want to initialize an object lazily, we should use it with by
keyword and lazy()
method.
In the onCreate
and onDestroy
lambda function, we can omit the this
keyword.
So we can use like below.
CompositeDisposable in RxJava2
Here is an example of CompositeDisposable
in RxJava2.
At the same time as initializing lazily the CompositeDisposable, the dispose()
method will be
invoked automatically when onDestroy.
Lifecycle related methods
We can invoke lambda functions as lifecycle changes and here are eight lifecycle-related methods of lifecycleAware
.
Usages in the non-lifecycle owner class
The lifecycleAware
is an extension of lifecycleOwner
so it can be used on non- lifecycle-owner classes.
LifecycleAwareProperty
If we don't need to initialize lazily, here is a more simple way.
We can declare a LifecycleAwareProperty
using the lifecycleAware
keyword.
The attribute value will not be initialized lazily. so we don't need to use it with by
keyword and lazy()
method.
And we can access the original property via the value
field.
We can observe the lifecycle changes using observe_
method.
Here is the kotlin dsl way.
Using in the non-lifecycle owner class
The lifecycleAware
is an extension of lifecycleOwner
so it can be used on non- lifecycle-owner classes.