在一個奇怪的場景中,我能夠從 API 獲取回應并通過觀察來自 viewmodel 的 livedata 在其中一個片段中看到它,但它沒有在不同的片段中顯示任何回應。
我有一個片段,我在其中放置了一些值,這些值進一步通過 viewmodel -> 存盤庫以從 api 獲取資料,然后我使用不同片段中的變數觀察這些資料。
我只能從我發送值的片段中獲取資料,但無法從其他片段中觀察。
這有什么可能的原因嗎?
PS - 如果有任何代碼要求,請告訴我我會添加。
編輯 1:發現應該使用一種稱為 Shared ViewModel 的東西。所以我嘗試實作它。我唯一需要改變的就是將我的viewModel實作更改為activityViewModels. 但事情似乎并沒有奏效。
不確定,但我在整個應用程式中實作 ViewModel 可能存在問題。
目前我遵循這種模式。來自 api 的資料 -> 存盤庫(我在其建構式中傳遞 api)-> ViewModel(我在其建構式中傳遞存盤庫)。
當我在 ViewModel 的建構式中傳遞存盤庫實體時,我創建了一個 ViewModelFactory,它在創建 ViewModel 時傳遞存盤庫。
記住這一切,我在MainApplication類中創建了一個全域初始化存盤庫,如下所示:
val myRepoInstance by lazy { myReposiotry(myApiClient) }
我在片段中實作它,如下所示:
private val myViewModelInstance: MyViewModel by activityViewModels {
ViewModelFactory((context?.applicationContext as MainApplication).myRepoInstance)
}
//Rest of the code...
uj5u.com熱心網友回復:
你需要工廠在你的第一個片段中,而不是在你的第二個片段中
對于第一個片段,請執行此操作
private val viewModel: SharedViewModel by activityViewModels { SharedViewModel.Factory(...) }
對于第二個片段執行此操作(不要創建工廠)
private val viewModel: SharedViewModel by activityViewModels()
有關此鏈接的詳細資訊![無法從一個片段觀察 Viewmodel 但適用于 Android [Kotlin] 中的不同片段](https://img.uj5u.com/2022/10/11/62b52b5f0e384a3a9c0f65f30db88129.png)
![無法從一個片段觀察 Viewmodel 但適用于 Android [Kotlin] 中的不同片段](https://img.uj5u.com/2022/10/11/597df5fce04e4c67b8d840f42032d67f.png)
在此處輸入影像描述 [
[![無法從一個片段觀察 Viewmodel 但適用于 Android [Kotlin] 中的不同片段](https://img.uj5u.com/2022/10/11/124971c0cfe24b4b881c0b6bd315c661.png)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513343.html
