title: Handling back button in MVVM architecture in Android
body: <p>I have two fragments A &amp; B set up with the Android Navigation Component. Fragment A contains a recyclerView in which an item click will navigate to Fragment B.</p>
  
  <p>The issue is when I click the up / back button inside Fragment B, it will not navigate back to Fragment A but will reload Fragment A and B. I still see Fragment B. </p>
  
  <p>In the Fragment A I've also floatingactionbutton which navigate to Fagment B and it works perfect. </p>
  
  <p>I also use ViewModel + DataBinding for RecyclerView.</p>
  
  <p>Here is how I've implemented navigation :
  Layout for item of Recyclerview</p>
  
  <pre><code>&lt;layout&gt;
  &lt;data&gt;
      &lt;import type="android.view.View"/&gt;
      &lt;variable
          name="position"
          type="java.lang.Integer" /&gt;
      &lt;variable
          name="viewModel"
          type="SmsListViewModel" /&gt;
  &lt;/data&gt;
  
  &lt;androidx.constraintlayout.widget.ConstraintLayout
     ...
      android:onClick="@{() -&gt; viewModel.onItemClick(position)}"&gt;
  &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
  &lt;layout&gt;
  </code></pre>
  
  <p>ViewModel:</p>
  
  <pre><code>private var clicked = MutableLiveData&lt;Long&gt;()
  fun getClicked(): MutableLiveData&lt;Long&gt; {
      return clicked
  }
  
  fun onItemClick(index: Int) {
      val threadId = smsList.value!!.get(index).threadId
      clicked.value = threadId
  }
  </code></pre>
  
  <p>Fragment A</p>
  
  <pre><code>smsListViewModel.getClicked().observe(this, Observer&lt;Long&gt; { clicked -&gt;
          if (clicked != null) {
              val action = SmsListFragmentDirections.actionListSmsToConservation(clicked)
              findNavController().navigate(action)
          }
      })
  </code></pre>
  
  <p>And code for button in Fragment A which it works:
  When I go to Fragment B and press up / back button I return to Fragment A.</p>
  
  <pre><code>floating_action_button.setOnClickListener { view -&gt;
          view.findNavController().navigate(R.id.nav_conservation)
      }
  </code></pre>
  
  <p>Where is problem? I try without Directions class but not helped. </p>