您可以先将实时数据创建为 Mutable 和 Immutable 两部分。可变的实时数据将仅在 viewModel 内部使用,而不可变的数据可以从片段或活动中观察到。
class CarViewModel: ViewModel() {
private val repo: EngineRepo() // an instance of your repository inside ViewModel
private val _engine = MutableLiveData<List<Engines>>() //mutable live data to be used inside the viewModel
val : LiveData<List<Engines>> = _engine //this is the observable live data
现在,
fun fetchEngineDetails() {
viewModelScope.launch(Dispatchers.IO){
_engine.postValue(repo.getEngine()) // calling the function inside your repo
}
}
现在你已经完成了你的 viewModel
因此,要在片段中调用此 ViewModel,假设您可以创建 ViewModel 类的实例。
class CarFragment: Fragment(){
private val carViewModel: CarViewModel by viewModels()
现在在您的 onCreate 方法中,您可以像这样使用 ViewModel 调用该函数:
varViewModel.fetchEngineDetails()
在 onCreateView 中,您可以像这样观察 livedata:
carViewModel.engine.observe {(viewlifeCycleOwner)} {
Toast.makeText(requireContext, "Number of engines is {it.size}, Toast.LENGTH_SHORT).show()
}
请注意,要按照我在此处编写的方式在片段中使用或创建 ViewModel 类的实例,您必须在您的 gradles 中放置一些依赖项
所以在你 build.gradle(项目)
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5"
在你的 build.gradle(App Module) 中
内部插件添加:
id 'androidx.navigation.safeargs.kotlin'
内部依赖添加:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation "android.arch.lifecycle:extensions:1.1.1"