I create ViewModel
with MutableLiveData<List<String>>
.
And I need to remove all items from it.
So I use clear function as below.
class MyViewModel : ViewModel() {
var regionModelData = MutableLiveData<List<String>>()
var regionDataList = regionModelData.value
var templateList = mutableListOf<String>()
fun addRegion(text: String) {
regionDataList?.forEach { data ->
templateList.add(data.toString())
}
templateList.add(text)
regionModelData.value = templateList
}
fun clearRegion() {
regionModelData.value = emptyList()
}
}
And I call clearRegion function before addRegion().
var regionRegister: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
regionModel.clearRegion()
var changeRegion = intent!!.getStringExtra("selectedRegion").toString()
Log.d("지역확인", "${changeRegion}")
regionDB
.document("4ggk4cR82mz46CjrLg60")
.collection("small_region")
.document(changeRegion)
.get()
.addOnSuccessListener { documents ->
documents.data?.forEach { (k, v) ->
regionModel.addRegion(v.toString())
}
Log.d("리지온", "${documents.data}", )
adapter.notifyDataSetChanged()
}
}
}
But regionModelData
keeps being added, not cleared at all.
How can I clear all items of list?
CodePudding user response:
The problem is that you have two different properties tracking the same data (regionModelData
and regionDataList
). regionDataList
is not going to automatically follow whatever the value is that's set inside the LiveData. You should just eliminate this property.
You are "clearing" the regionDataList
by replacing it with a new empty list in the ViewModel, but other classes that reference the original List don't know anything about that var
property and are still referencing the original instance.
You should remove regionDataList
and templateList
, and update the adapter in an observe
call on your LiveData, so it always gets notified of the latest value.
Your addRegion
function can be revised as follows:
fun addRegion(text: String) {
regionModelData.value = regionModelData.value text
}