I'm following this article https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c to implement android lifecycle but on a legacy app that has the Application class on java.
How can I implement this kotlin code in java?
private val lifecycleListener: SampleLifecycleListener by lazy {
SampleLifecycleListener()
}
I feel that is a dumb question, but I'm not familiar with lazy initialization and I'm not sure how to search this question, any "lazy theory link" will be welcome also.
You can call Kotlin lazy
from Java if you want to:
import kotlin.Lazy;
Lazy<SampleLifecycleListener> lazyListener = kotlin.LazyKt.lazy(() -> new SampleLifecycleListener()));
SampleLifecycleListener realListener = lazyListener.getValue();
private SampleLifecycleListener sll;
public synchronized SampleLifecycleListener getSampleLifecycleListener() {
if (sll == null) {
sll = new SampleLifecycleListener();
}
return sll;
}
That way it isn't initialized until the getter is called.
Beginning with Java 8, you can use ConcurrentHashMap#computeIfAbsent()
to achieve laziness. ConcurrentHashMap
is thread-safe.
class Lazy {
private final ConcurrentHashMap<String, SampleLifecycleListener> instance = new ConcurrentHashMap<>(1);
public SampleLifecycleListener getSampleLifecycleListener() {
return instance.computeIfAbsent("KEY", k -> new SampleLifecycleListener()); // use whatever constant key
}
}
You can use this like
SampleLifecycleListener sll = lazy.getSampleLifecycleListener();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With