【问题标题】:Android Kotlin - inherit a VIewModel from another ViewModelAndroid Kotlin - 从另一个 ViewModel 继承一个 VIewModel
【发布时间】:2020-02-05 11:53:13
【问题描述】:

我用 BaseActivity 和 BaseViewModel 在应用程序中创建了一个结构。所有其他活动/视图模型必须使用此基类进行扩展。我这样做是因为我需要在任何活动中调用一些方法(如 showInfo() 方法)。

当我在 BaseViewModel 中更新 LiveData 并在 BaseActivity 中观察它时,一切正常。但是,当我仅在 BaseActivity 观察的情况下更新子 ViewModel(例如 UsersViewModel)中的 LiveData 时,它将不起作用。

当我想通过 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")
     }
}

【问题讨论】:

    标签: android kotlin android-livedata android-viewmodel


    【解决方案1】:

    仅仅通过扩展 UserViewModel 你的 BaseViewModel,并不意味着它共享同一个实例。根据您的要求,我认为您需要一个可以将其实例共享给多个 Activity 的 ViewModel,这样当您在 Activity A 上更新 ViewModel 时,您可以观察到 Activiy B 上的变化,等等。

    这就是 SharedViewModel 来拯救的地方。您需要为所有活动实现 sharedViewModel。

    private val baseViewModel: BaseViewModel by sharedViewModel()
    

    参考:https://doc.insert-koin.io/#/koin-android/viewmodel?id=shared-viewmodel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多