title: Authentication Flow Using Android Navigation Component
body: <p>Today I've started playing with Android's Navigation Component to implement authentication flow in my app. The idea is very simple: a user launches the app and it displays one piece of UI if she's authenticated and another if she's not.</p>
  
  <p>What I've done is in my <code>HomeFragment</code>'s <code>onViewCreated</code> method I check if a user is authenticated and if she's not I call the <code>NavController</code>'s <code>navigate()</code> method by passing it the id of an action that will navigate to the <code>AuthenticationFragment</code>. Everything works fine until a user clicks the back button while in <code>AuthenticationFragment</code>, because then I get <a href="https://stackoverflow.com/questions/51060762/java-lang-illegalargumentexception-navigation-destination-xxx-is-unknown-to-thi">this error</a>. I still have no idea what's the actual reason for that error, but the idea of navigation happening too quickly seems similar to my case: the destinations first switch from <code>AuthenticationFragment</code> to <code>HomeFragment</code> and then immediately from <code>HomeFragment</code> to <code>AuthenticationFragment</code> again, because <code>HomeFragment</code> finds out again that a user is not authenticated.</p>
  
  <p>Despite of the error I'm getting, this approach still seems wrong to me. The user shouldn't be able to go back to the <code>HomeFragment</code> (and see the screen flicker when fragments are immediately switching back and forth) before she authenticates. I've also looked at this <a href="https://developer.android.com/guide/navigation/navigation-conditional" rel="noreferrer">Android's official guide to implementing an authentication flow</a>, but it too seems wrong to me, because a redundant third piece of UI is involved there (the <code>MainFragment</code>). I could replace it with a splash screen in my case, but it would still stay in the back stack and the user would be able to go back to splash screen, which is obviously nonsense.</p>
  
  <p>So what would be the correct way to implement an authentication flow using the Android's new Navigation Component? The functionality I want is: if a user is not authenticated, then she's redirected to an authentication UI and if she presses the back button from there she should exit the application.</p>
  
  <p><strong>UPDATE:</strong> I know I could just listen to the back press event and close the application from there, but I still hope there's some elegant solution using Android's Navigation Component.</p>