简体   繁体   中英

Android Kotlin - inherit a VIewModel from another ViewModel

I've created a structure in app with BaseActivity and BaseViewModel. All other activities/viewModels must be extend with this base classes. I made that cause i need to call some methods in any activity (like showInfo() method).

When i update LiveData in BaseViewModel and observe it in BaseActivity all works well. But when i update that LiveData in child ViewModel (eg UsersViewModel) only with BaseActivity observing its won't work.

What should i do when i want to call some base method in any activity through 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")
     }
}

Just by extend the UserViewModel your BaseViewModel, doesn't mean it's sharing the same instance. Based on your requirement, I think you need a ViewModel that can share it's instance to several activity, so that when you update the ViewModel on Activity A, you can observe the change on Activiy B, and so on.

This is where SharedViewModel come to rescue. You need to implement a sharedViewModel to all your activity.

private val baseViewModel: BaseViewModel by sharedViewModel()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM