Allow ViewModel injection from the MainActivity.

This commit is contained in:
Kevin Gorham 2020-08-27 20:19:07 -04:00
parent 22d3e19ddf
commit 35d268622c
No known key found for this signature in database
GPG Key ID: CCA55602DF49FC38
1 changed files with 23 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package cash.z.ecc.android.di.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import cash.z.ecc.android.ui.MainActivity
import cash.z.ecc.android.ui.base.BaseFragment
@ -35,4 +36,26 @@ inline fun <reified VM : ViewModel> BaseFragment<*>.activityViewModel(isSynchron
inline fun <reified VM : ViewModel> BaseFragment<*>.scopedFactory(isSynchronizerScope: Boolean = true): ViewModelProvider.Factory {
val factory = if (isSynchronizerScope) mainActivity?.synchronizerComponent?.viewModelFactory() else mainActivity?.component?.viewModelFactory()
return factory ?: throw IllegalStateException("Error: mainActivity should not be null by the time the ${VM::class.java.simpleName} viewmodel is lazily accessed!")
}
/**
* Create a viewModel that is scoped to the lifecycle of the activity. This viewModel will be
* created from the `synchronizerComponent` rather than the `component`, meaning the synchronizer
* will be available but this also requires that this view model not be accessed before the
* synchronizerComponent is ready. Doing so will throw an exception.
*/
inline fun <reified VM : ViewModel> MainActivity.activityViewModel() = object : Lazy<VM> {
val cached: VM? = null
override fun isInitialized(): Boolean = cached != null
override val value: VM
get() {
return cached
?: this@activityViewModel.run {
if (isInitialized) {
ViewModelProvider(this, synchronizerComponent.viewModelFactory())[VM::class.java]
} else {
throw IllegalStateException("Error: the SynchronizerComponent must be initialized before the ${VM::class.java.simpleName} viewmodel is lazily accessed!")
}
}
}
}