Skip to content

Instantly share code, notes, and snippets.

@DaChelimo
Created December 3, 2020 08:14
Show Gist options
  • Save DaChelimo/b495a4d947a11d5a2d361766fc203949 to your computer and use it in GitHub Desktop.
Save DaChelimo/b495a4d947a11d5a2d361766fc203949 to your computer and use it in GitHub Desktop.
A kotlin extension function that eliminates the need of writing ViewModelFactory
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
/**
* An extension function that removes the need to write ViewModelFactory by creating a factory based on ViewModel arguments
*
* Example:
* private val viewModel: DailyForecastViewModel by DailyForecastViewModel(requireContext()).createViewModel(this)
*/
inline fun <reified VM : ViewModel> ViewModel.createViewModel(fragment: Fragment): Lazy<VM> {
return lazy {
ViewModelProvider(fragment.viewModelStore,
object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return this@createViewModel as T
}
}
).get(VM::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment