共享实时数据观察器无法在 Fragment 和 Activity 之间工作

Shared livedata observer not working between Fragment and Activity

我有一个视图模型,它是在我的 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
        })
    }

并且我在另一个片段中更改了 '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
        }
    }

值确实在改变,但从未调用观察者。

我不知道哪里出了问题,我错过了什么。

尝试使用 Koin 的 'get<>()' 方法而不是 'by inject()' 但没有帮助。

您需要使用

// Activity
private val sharedInformationViewModel: SharedInformationViewModel by viewModel()

// Fragment
private val sharedInformationViewModel: SharedInformationViewModel by sharedViewModel()

= module {
    viewModel {
        SharedInformationViewModel()
    }
}

根据official documentation,viewModel应该初始化为:

 //Use the 'by activityViewModels()' Kotlin property delegate
 // from the fragment-ktx artifact

 private val model: SharedViewModel by activityViewModels()