我正在使用MVVM,并对其进行了不同的实现,但是有一件事仍然让我感到怀疑,那就是如何在不将任何生命周期附加到视图模型的情况下,从我的视图模型中获取存储库(Firebase)中的数据.
我已经从视图模型实现了observeForever()
,但我认为这不是一个好主意,因为我认为我应该通过回调或转换从存储库与视图模型通信.
I leave here an example where I fetch a device from Firebase and update my 用户界面, if we can see here, I'm observing the data coming from the repo from the 用户界面, but from the 视图模型 I'm also observing data from the repo, and here is where I really doubt if I'm using the right approach, since I don't know if observeForever()
will be cleared on onCleared()
if my view is destroyed, so it won't keep the observer alive if the view dies.
用户界面
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
val deviceId = editText.text.toString().trim()
observeData(deviceId)
}
}
fun observeData(deviceId:String){
viewModel.fetchDeviceData(deviceId).observe(this, Observer {
textView.text = "Tipo: ${it.devType}"
})
视图模型
class MainViewmodel: 视图模型() {
private val repo = Repo()
fun fetchDeviceData(deviceId:String):LiveData<Device>{
val mutableData = MutableLiveData<Device>()
repo.getDeviceData(deviceId).observeForever {
mutableData.value = it
}
return mutableData
}
}
Repository
class Repo {
private val db = FirebaseDatabase.getInstance().reference
fun getDeviceData(deviceId:String):LiveData<Device>{
val mutableData = MutableLiveData<Device>()
db.child(deviceId).child("config/device").addListenerForSingleValueEvent(object: ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
val device = dataSnapshot.getValue(Device::class.java)
mutableData.value = device
}
override fun onCancelled(dataError: DatabaseError) {
Log.e("Error","handle error callback")
}
})
return mutableData
}
}
这个例子只是展示了如何从Firebase获取设备,它是有效的,但是从我的视图模型来看,它让我一直认为observeForever()
不是我要在存储库和视图模型之间进行数据通信的地方.
I have seen Transformations
, but I, in this case, I just need to deliver the entire Device object to my 用户界面, so I don't need to transform the Object I'm retrieving to another Object
这里应该有什么正确的方法来正确地沟通存储库和视图模型?