[英]Shared livedata observer not working between Fragment and Activity
I have a viewmodel that is instantiated via Koin library at my MainActivity -我有一个通过我的 MainActivity 中的 Koin 库实例化的视图模型 -
class SharedInformationViewModel : ViewModel() {
val deviceId : MutableLiveData<String> = MutableLiveData<String>()
}
class MainActivity : AppCompatActivity() {
private val sharedInformationViewModel: SharedInformationViewModel by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
setContentView(binding.root)
sharedInformationViewModel.deviceId.observe(this, { deviceId ->
//This is not called no matter what I do!
val x = 5
})
}
And I changed the value of 'deviceId' in another Fragment -我在另一个片段中更改了“deviceId”的值 -
class SettingsFragment : Fragment() {
private val sharedInformationViewModel: SharedInformationViewModel by inject()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Alot of code here ...
if (deviceId != activity?.sharedPreferences?.deviceId) {
sharedInformationViewModel.deviceId.value = deviceId
activity?.sharedPreferences?.deviceId = deviceId
wasSettingsDataChanged = true
}
}
The value indeed is getting changed but the observer is never called.该值确实在发生变化,但从未调用过观察者。
I can't figure out what's wrong and what is it that I am missing.我不知道出了什么问题,我错过了什么。
Tried to use Koin's 'get<>()' method instead of 'by inject()' but did not help.尝试使用 Koin 的 'get<>()' 方法而不是 'by inject()' 但没有帮助。
You need to use你需要使用
// Activity
private val sharedInformationViewModel: SharedInformationViewModel by viewModel()
// Fragment
private val sharedInformationViewModel: SharedInformationViewModel by sharedViewModel()
And和
= module {
viewModel {
SharedInformationViewModel()
}
}
According to official documentation , viewModel should be initialize as:根据官方文档,viewModel 应该被初始化为:
//Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.