![](/img/trans.png)
[英]Must a ViewModel class inherit from ViewModel() in Android Jetpack?
[英]Android Kotlin - inherit a VIewModel from another ViewModel
我在應用程序中使用 BaseActivity 和 BaseViewModel 創建了一個結構。 所有其他活動/視圖模型都必須使用此基類進行擴展。 我這樣做是因為我需要在任何活動中調用一些方法(如 showInfo() 方法)。
當我在 BaseViewModel 中更新 LiveData 並在 BaseActivity 中觀察它時一切正常。 但是當我更新子 ViewModel(例如 UsersViewModel)中的 LiveData 時,僅使用 BaseActivity 觀察它是行不通的。
當我想通過 ViewModel 在任何活動中調用一些基本方法時應該怎么做?
open class BaseActivity : AppCompatActivity() {
//inject viewModel with Koin
private val baseViewModel: BaseViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
baseViewModel.actionShowInfo.observe(this, Observer {
showInfo(it)
}
}
protected fun showInfo(message: String) {
AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton(R.string.ok, null)
.show()
}
}
open class BaseViewModel : ViewModel() {
private val actionShowInfo = MutableLiveData<String>()
init {
actionShowInfo.postValue("some base info") //showInfo() in BaseActivity will be called
}
}
class UsersActivity : BaseActivity() {
private val usersViewModel: UsersViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(
}
}
class UsersViewModel: BaseViewModel {
init {
//showInfo() in BaseActivity will not be called
actionShowInfo.postValue("some info")
}
}
僅僅通過擴展 UserViewModel 你的 BaseViewModel,並不意味着它共享同一個實例。 根據您的要求,我認為您需要一個可以將其實例共享給多個活動的 ViewModel,以便當您更新 Activity A 上的 ViewModel 時,您可以觀察到 Activity B 上的變化,依此類推。
這就是 SharedViewModel 來拯救的地方。 您需要為所有活動實現一個 sharedViewModel。
private val baseViewModel: BaseViewModel by sharedViewModel()
參考: https : //doc.insert-koin.io/#/koin-android/viewmodel?id=shared-viewmodel
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.