以下の記述ですが、
private val viewModel: MainViewModel by lazy {
ViewModelProviders.of(this).get<MainViewModel>()
}
Activityで にしろ、Fragmentで にしろ、
private val viewModel: MainViewModel by viewModels()
でいける。
Fragment内で呼び出す場合は、
dependencies {
implementation 'androidx.fragment:fragment-ktx:1.1.0-alpha08'
}
で、今現在。
コードをみてみる。
@MainThread
inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
@MainThread
inline fun <reified VM : ViewModel> Fragment.activityViewModels(
noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { requireActivity().viewModelStore }, factoryProducer)
@MainThread
fun <VM : ViewModel> Fragment.createViewModelLazy(
viewModelClass: KClass<VM>,
storeProducer: () -> ViewModelStore,
factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val factoryPromise = factoryProducer ?: {
val application = activity?.application ?: throw IllegalStateException(
"ViewModel can be accessed only when Fragment is attached"
)
AndroidViewModelFactory.getInstance(application)
}
return ViewModelLazy(viewModelClass, storeProducer, factoryPromise)
}
使ったほうが良いですよね。
はまらなくてすむ。