Created
December 3, 2020 08:14
-
-
Save DaChelimo/b495a4d947a11d5a2d361766fc203949 to your computer and use it in GitHub Desktop.
A kotlin extension function that eliminates the need of writing ViewModelFactory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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