1
votes

I confused with MVVM concept that ViewModel should not reference View.
In my usecase , I have to use Databinding and wrapping the Drawable by LiveData and observe its value in xml view.

Base on suggestion from Android I implemented as below
https://developer.android.com/topic/libraries/architecture/viewmodel

If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.

MyViewModel.kt

class MyViewModel(application: Application): AndroidViewModel(application){  
  private val _showIcon = MutableLiveData<Drawable>  
  val showIcon: LiveData<Drawable>  
    get() = _showIcon

  fun applyChanged(){
     if(condition){
       _showIcon.value = AppCompatResources.getDrawable(getApplication(),R.drawable.icon1)
     }else{
       _showIcon.value = null
     }
  }
}

main_activity.xml

   android:drawableTop="@{viewModel.showIcon}"

Question:
This approach is OK with MVVM concept ? Is there anything I have to do with context inside ViewModel to prevent leak memory problem?
Or any potential problem in my code ?

Thank you so much !

1
What if you make BindingAdapter for your drawable loading. In such a way, you can prevent memory leaks for storing context in ViewModel. - Jeel Vankhede
How to make BindingAdapter in my case ? - Bulma
Please refer here : developer.android.com/topic/libraries/data-binding/…, let me know if problem persist. - Jeel Vankhede
@JeelVankhede I already tried and it worked ! Thank you. But it's not my purpose, I am confused about my approach that has potential problem or it against MVVM concept ??? - Bulma
@JeelVankhede As far as I know, ViewModel should not refer Activity context because viewModel and Activity's lifecycle is difference. But Application's context is OK because Application and ViewModel is same lifecycle. Is that correct ? - Bulma

1 Answers

1
votes

I don't see any need to use databinding or view models for what you want to do. Just refer the drawable directly in xml file. If it is null, it won't be there. This is valid because you are getting the image resource from your own resources. If you were supposed to get any drawable from server or local database your approach would make sense.