Created
November 7, 2018 18:04
-
-
Save alexmprog/460f5b2371a041f36b56c88195522424 to your computer and use it in GitHub Desktop.
Extensions function for getting ViewModels
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
| class BaseViewModelFactory<T>(val creator: () -> T) : ViewModelProvider.Factory { | |
| override fun <T : ViewModel?> create(modelClass: Class<T>): T { | |
| return creator() as T | |
| } | |
| } |
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
| private const val USER_ID = "user_id_key" | |
| class UserActivity : AppCompatActivity() { | |
| val vm by lazy { | |
| getViewModel { UserViewModel(intent.getIntExtra(USER_ID, -1)) } | |
| } | |
| override fun onCreate(savedInstanceState: Bundle?) { | |
| super.onCreate(savedInstanceState) | |
| } | |
| } |
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
| inline fun <reified T : ViewModel> Fragment.getViewModel(noinline creator: (() -> T)? = null): T { | |
| return if (creator == null) | |
| ViewModelProviders.of(this).get(T::class.java) | |
| else | |
| ViewModelProviders.of(this, BaseViewModelFactory(creator)).get(T::class.java) | |
| } | |
| inline fun <reified T : ViewModel> FragmentActivity.getViewModel(noinline creator: (() -> T)? = null): T { | |
| return if (creator == null) | |
| ViewModelProviders.of(this).get(T::class.java) | |
| else | |
| ViewModelProviders.of(this, BaseViewModelFactory(creator)).get(T::class.java) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment