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 !
ViewModel. - Jeel Vankhede