Skip to content

Instantly share code, notes, and snippets.

@AniketSK
Created October 15, 2019 06:27
Show Gist options
  • Save AniketSK/5b13e4f0c67b2ab14e0d48d587dc5e0e to your computer and use it in GitHub Desktop.
Save AniketSK/5b13e4f0c67b2ab14e0d48d587dc5e0e to your computer and use it in GitHub Desktop.
Demos using a listener for a data source and also an editable field.
val <T> T.exhaustive: T
get() = this
mainActivityVm.currentFragment.observe(this, Observer(::setScreen))
private fun setScreen(screen: Screen) =
with(findNavController(R.id.nav_host_fragment_container)) {
when (screen) {
Screen.SPLASH -> { /*is default and never returns here*/
}
Screen.FROM_SPLASH_TO_LIST -> safeNavigate(SplashFragmentDirections.actionSplashFragmentToGoalFragment())
Screen.FROM_ADD_TO_LIST -> safeNavigate(AddGoalFragmentDirections.actionAddGoalFragmentToGoalFragment())
Screen.ADD -> safeNavigate(GoalsListFragmentDirections.actionGoalFragmentToAddGoalFragment())
}.exhaustive
}
private fun NavController.safeNavigate(d: NavDirections) =
currentDestination?.getAction(d.actionId)?.let { navigate(d) }
?: Timber.e("Invalid route for direction ${d} with id ${d.actionId}")
private val _currentFragment = MutableLiveData<Screen>(Screen.SPLASH)
/**
* The current fragment is determined by two factors:
* 1. The move from the splash screen to the main fragment happens when authentication is complete
* 2. Any subsequent navigations are guided by code that modifies _currentFragment, the private
* mutable livedata.
*/
val currentFragment: LiveData<Screen> = MediatorLiveData<Screen>().apply {
addSource(repository.isAuthenticated) { authenticated ->
if (authenticated) {
value = Screen.FROM_SPLASH_TO_LIST
}
}
addSource(_currentFragment) { value = it }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment