Last active
June 11, 2020 11:38
-
-
Save thegarlynch/29303008fc291fad9a79264051b56580 to your computer and use it in GitHub Desktop.
ViewModel Helper Untuk Android
This file contains 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.annotation.IdRes | |
import androidx.fragment.app.Fragment | |
import androidx.fragment.app.FragmentActivity | |
import androidx.lifecycle.ViewModel | |
import androidx.lifecycle.ViewModelProvider | |
import androidx.navigation.fragment.findNavController | |
/** | |
* This extension is best used when using | |
* [dagger.hilt.android.AndroidEntryPoint] + | |
* [androidx.hilt.lifecycle.ViewModelInject] + | |
* [androidx.hilt.Assisted] | |
* as it will resolves SavedStateHandle automatically | |
* | |
* @sample | |
* | |
* class ExampleViewModel @ViewModelInject constructor( | |
* @Assisted handle : SavedStateHandle | |
* ) | |
* | |
* @AndroidEntryPoint | |
* class ExampleFragment : Fragment { | |
* | |
* val viewModel : ExampleViewModel by viewModel() | |
* | |
* } | |
* | |
* | |
*/ | |
inline fun <reified VM : ViewModel> FragmentActivity.viewModel() : Lazy<VM>{ | |
return lazy { ViewModelProvider(this).get(VM::class.java) } | |
} | |
inline fun <reified VM : ViewModel> Fragment.viewModel() : Lazy<VM>{ | |
return lazy { ViewModelProvider(this).get(VM::class.java) } | |
} | |
inline fun <reified VM : ViewModel> Fragment.activityViewModel() : Lazy<VM> { | |
return lazy { ViewModelProvider(requireActivity()).get(VM::class.java) } | |
} | |
inline fun <reified VM : ViewModel> Fragment.navGraphViewModel(@IdRes id : Int) : Lazy<VM>{ | |
val navController = findNavController() | |
val backStackEntry = navController.getBackStackEntry(id) | |
return lazy { ViewModelProvider(backStackEntry).get(VM::class.java) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment