1

There is a project written by another programmer. And in it there is such a code

class CardsViewModel : ViewModel() {
    val selected = MutableLiveData<PaymentCard>()

    companion object {
        @JvmStatic
        var keyId = 0
    }
}

Every time some data is added to the ViewModel, this keyId is incremented:

val cardsViewModel = ViewModelProviders.of(requireActivity())
                    .get(CardsViewModel.keyId.toString(), CardsViewModel::class.java)
                CardsViewModel.keyId++
                cardsViewModel.selected.value = PaymentCard.EMPTY

Then gets it this way:

val cardsViewModel = ViewModelProviders.of(requireActivity()).get(CardsViewModel.keyId.toString(), CardsViewModel::class.java)
 bindingId = cardsViewModel.selected.value?.bindingId ?: ""

I just recently started learning LiveData and it’s unclear to me what this id gives and how to work with it? I got the impression that I put the data tied to some key and then retrieve it using this key =) But this causes a lot of questions.

P.S. The project was written poorly, so maybe this is some kind of crutch, but due to lack of experience with LiveData, I cannot understand this

Sergei Buvaka
  • 551
  • 1
  • 5
  • 16
  • 1
    For sure it is bad practice to use static variable, it may cause memory leaks – Antonis Radz Jul 01 '19 at 06:58
  • But I still do not understand how to work with it in principle? – Sergei Buvaka Jul 01 '19 at 07:02
  • instead of that static variable some shared model should be used for accessing key value or even SharedPreferences – Antonis Radz Jul 01 '19 at 07:04
  • If it is necessary for your project and you dont want to (or dont have time) to change it, just stay with it, but change it to AtomicInteger. About key, as documentation says `key The key to use to identify the ViewModel.`, so it is just id of ViewModel, probably used in other parts of your project. – Ikazuchi Jul 01 '19 at 07:08
  • Instead you should use a `viewmodel factory` to pass key id as a constructor param – алекс кей Sep 28 '22 at 10:47

0 Answers0