I have implemented the entire structure of an MVVM architecture with jetpack but I don't know how to observe each position of an array, to observe a property it is only done like this:
var normales=""
@Bindable get
set(v){
field=v
notifyPropertyChanged(BR.normales)
}
With an array of type map<String, String> I would need the index because it would not be convenient to go through the entire array to know which change, to observe the change I have it like this:
inner class ArrayWrapper(vararg pairs: Pair<String, String>) :LinkedHashMap<String, String>(pairs.size) {
override fun put(key: String, value: String): String {
notifyPropertyChanged(BR.calibre)
return super.put(key,value)!!
}
}
var calibre= ArrayWrapper("C2" to "", "C3" to "", "C4" to "", "C5" to "", "C6+" to "")
@Bindable get
This works very well but currently I have the observer like this:
viewModel.addOnPropertyChangedCallback(object: Observable.OnPropertyChangedCallback(){
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
when(propertyId){
BR.calibre-> Log.i("cambio calibres","asi "+ viewModel.calibre.toString())
else-> Log.i("hola","notificaron")
}
}
})
and the output gives me:
I/cambio calibres: asi {C2=56, C3=4, C4=, C5=, C6+=}
I/cambio calibres: asi {C2=56, C3=4, C4=, C5=5, C6+=}
So how can I know which index changed?
Before I answer, I'm going to show you how to improve the way you create observables because you're writing a lot of unnecessary code. Your programming sense should be able to detect that your solution is too complex for such a simple problem.
Unnecessary things you are doing:
ArrayWrapper
@Bindable
Observable
So what is the correct way to implement it? The answer is in the documentation
All you have to do is wrap
LiveData
whatever object you want to observe in aNow the solution to know which index changed is to add another observable property
Then in your activity you see it like this