HelloCW
HelloCW

Reputation: 2235

What are different between two ways of initial MutableLiveData in Kotlin?

Both Code A and Code B init a variable MutableLiveData.

In my mind

_playA can be null, and _playA?.value can not be null

_playB can be null, and _playB?.value can be null

right?

Code A

private val _playA = MutableLiveData(EPlayState.STOPPED)

Code B

private val _playB = MutableLiveData<EPlayState>()

Both

enum class EPlayState {
    STOPPED,
    PLAYING,
    PAUSED
}

Added content

From the prompt information in Android Studio, you will find val a and val b can be null.

Image A

enter image description here

Image B

enter image description here

Upvotes: 0

Views: 205

Answers (2)

Tobi
Tobi

Reputation: 888

You are right that when calling

private val _playA = MutableLiveData(EPlayState.STOPPED)

_playA.value is not null. BUT it can be null after calling _playA.setValue(null)

As the others already said, the MutableLiveData object itself will not be null as you initialized it. But as you said, in theory you could still call _playA = null and therefore it can be null.

Upvotes: -1

Debarshi Bhattacharjee
Debarshi Bhattacharjee

Reputation: 830

A LiveData or MutableLiveData is just a wrapper over your actual data. Data can be any type. You wrap your data with LiveData so that when the value in LiveData changes, it trigges the Observer listening to it. (For better understanding see OBSERVER DESIGN PATTERN)

Now answering your questions,

_playA can be null, and _playA?.value can not be null _playB can be null, and _playB?.value can be null right?

Both play _playA and _playB cannot be null as you've already initialized them with MutableLiveData.

_playA and _playB are referring to the instance of the MutableLiveData.

From the prompt information in Android Studio, you will find val a and val b can be null

Yes, both val a and val b can be null beacuse they're referring to the value held by the MutableLiveData and not to the instance of MutableLiveData.

As, MutableLiveData and LiveData is a wrapper class (that is, holds another class), we can initialize a MutableLiveData by specifying the type it should hold.

Example- val isBool:MutableLiveData<Boolean>=MutableLiveData()

In this case, isBool.value will give null since only the type has been specified but no value has been set.

But

When I do, val isBool:MutableLiveData<Boolean> = MutableLiveData(true) // passed a boolean value to MutableLiveData constructor

isBool.value will give true as I had initialized it with Boolean value true

Same stands in your cases.

Upvotes: 2

Related Questions