Home>

There is such a code withbyLazyandLiveData.
And it crashes. Says that"listMyTrades.value== null"

val emptyDepositListBean: DepositListBean by lazy {
        val dbl= DepositListBean ()
        dbl.deposits= mutableListOf ()
        dbl
    }
var listMyTrades= MutableLiveData <
DepositListBean >
() .apply {value= emptyDepositListBean}

If you replacebyLazyonapply, then everything will work correctly:

val emptyDepositListBean: DepositListBean= DepositListBean (). apply {deposits= mutableListOf ()}
var listMyTrades= MutableLiveData <
DepositListBean >
() .apply {value= emptyDepositListBean}

Actually the question is: should it be so?
unless a linevalue= emptyDepositListBeanshould not force to holdLazyinitialization and then put inLiveData?

Try to make listMyTrades by lazy too. It is now initialized at the time of object creation, there may be subtleties with the initialization of the used lazy properties

Alex_Skvortsov2021-09-24 01:15:11

why do you need lazy if you immediately use this property? plus MutableLiveData has a constructor to which you can pass an initial value, so apply doesn't need MutableLiveData (emptyDepositListBean)

IR422021-09-24 01:15:11

@ IR42 the question is not about "how to do it", but "why does lazy behave this way". just for me, this behavior is not obvious. so I want to understand how byLazy works

Wlad2021-09-24 01:15:11

In general, everything is fine in the above code, can you add at least the code where it crashes? Do you have exactly listMyTrades below emptyDepositListBean? What version of Kotlin?

IR422021-09-24 01:15:11

@ IR42 is exactly below. Kotlin 1.5.20. A crash occurs when the LiveData listener climbs into value and does not find an initialized array there. those. listMyTrades.value== null

Wlad2021-09-24 01:15:11