I've seen people doing: ``` private val _foo by la...
# android
g
I've seen people doing:
Copy code
private val _foo by lazy { MutableLiveData()}

val foo: LiveData by lazy { _foo } // why second lazy?
Does this second lazy really make sense? Seems like
val foo: LiveData = _foo
val foo: LiveData get() = _foo
should be enough.
m
I think
val foo: LiveData = _foo
would initialize
_foo
immediately. To keep it all lazy,
foo
must be lazy as well.
g
val foo: LiveData get() = _foo
?
m
That should work I think. Try it to see what happens.
g
yep, the lazy is redundant: https://pl.kotl.in/rko7o8XfN
another question is tho, if you have transformations:
Copy code
val foo: LiveData get() = _foo.map{}...

vs

val foo: LiveData by lazy { _foo.map{}... }
I suppose in this case
lazy
will cache the map lambda?
a
Correct. You can look at the source and see that lazy will only execute the block if the stored value is
UNINITIALIZED
r
No need for 2nd lazy
h
I couldn’t understand why lazy is used to init LiveData. I know what it does but why?
g
You won't gain much if it's a livedata that is being observed all the time the view is alive. But you can have some livedatas that you subscribe to under a certain condition, so if condition is false — you don't create it for nothing.
a
I haven't really used it (I've been trying Channels instead), but given livedata is the observable, aren't you going to inevitably send data to it?
g
not, unless you observe it. It's pretty much a very primitive version of Rx stream (BehaviorSubject).
a
How are you going to post events without initializing the livedata? Whether or not you use the events is a different story. Similarly with publish/behavior subject and channels; wasn't the point that the observable did not have to be aware of the observers when sending content?
h
Thanks for explaining.