使用LiveData在ViewModel之间传递数据是一种有效的方法。以下是实现此目的的步骤:
class SharedViewModel : ViewModel() {
val sharedData = MutableLiveData()
}
class SenderViewModel(private val sharedViewModel: SharedViewModel) : ViewModel() {
fun sendData(data: String) {
sharedViewModel.sharedData.value = data
}
}
class ReceiverViewModel(private val sharedViewModel: SharedViewModel) : ViewModel() {
val receivedData = sharedViewModel.sharedData
}
4.现在,通过发送ViewModel发送数据并在接收ViewModel中观察数据即可实现在ViewModel之间共享数据。
//inside Activity or Fragment
val sharedViewModel: SharedViewModel by viewModels()
val senderViewModel: SenderViewModel by viewModels { parametersOf(sharedViewModel) }
val receiverViewModel: ReceiverViewModel by viewModels { parametersOf(sharedViewModel) }
//send data
senderViewModel.sendData("Hello World!")
//observe data
receiverViewModel.receivedData.observe(viewLifecycleOwner, { data ->
//do something with received data
})
这样,我们就可以在不同的ViewModel之间共享数据,并保持MVVM的分离性和低耦合性。