Search code examples
androidandroid-livedataandroid-architecture-componentsplaid

LiveData confusion in [Android] Plaid App


I am referring to the Plaid open source project on github Link to Plaid

It is an excellent source to learn new techniques on Android.

As I was going through the code, I came across a certain style of coding around LiveData which I really didn't understand. If anybody can help me get it. Here goes:

There's a ViewModel(vm) with this piece of code:

private val _openLink = MutableLiveData<Event<String>>()
val openLink: LiveData<Event<String>>
    get() = _openLink

Fairly simple? Note that, there are 2 variables here: openLink and _openLink. The getter for openLink is returning the _openLink LiveData.

In the activity they observe the openLink LiveData as follows:

viewModel.also { vm ->

       vm.openLink.observe(this, EventObserver { openLink(it) })

        ..... // Other stuff
}

Now, the other livedata _openLink is being called by the UI supposedly on a button click and it's defined like this:

fun viewShotRequested() {
    _shotUiModel.value?.let { model -> // ignore this part
        _openLink.value = Event(model.url) // setValue on _openLink
    }
}

So here my understanding is, on setValue() on _openLink, EventObserver{openLink(it)} will get called. My question is, why have they done it like this?

Questions:

  1. Why not observe directly on _openLink?

  2. Will it not have the same effect? What am I missing here?


Solution

  • _openLink is mutable. You must always expose something which is immutable and cannot be changed by your observer, because that should only be done by your ViewModel, even though exposing _openLink would have no effect.

    That's why you need to expose openLink which is immutable.

    private val _openLink = MutableLiveData<Event<String>>()
    val openLink: LiveData<Event<String>> = _openLink