title: MVVM pattern and startActivity
body: <p>I recently decided to have a closer look at the new Android Architecture Components that Google released, especially using their ViewModel lifecycle-aware class to a MVVM architecture, and LiveData.</p>
  
  <p>As long as I'm dealing with a single Activity, or a single Fragment, everything is fine.</p>
  
  <p>However, I can't find a nice solution to handle Activity switching.
  Say, for the sake of a short example, that Activity A has a button to launch Activity B.</p>
  
  <p><strong>Where would the startActivity() be handled?</strong></p>
  
  <p>Following the MVVM pattern, the logic of the clickListener should be in the ViewModel. However, we want to avoid having references to the Activity in there. So passing the context to the ViewModel is not an option.</p>
  
  <p>I narrowed down a couple of options that seem "OK", but was not able to find any proper answer of "here's how to do it.".</p>
  
  <p><strong>Option 1</strong> : Have an enum in the ViewModel with values mapping to possible routing (ACTIVITY_B, ACTIVITY_C). Couple this with a LiveData.
  The activity would observe this LiveData, and when the ViewModel decides that ACTIVITY_C should be launched, it'd just postValue(ACTIVITY_C). Activity can then call startActivity() normally.</p>
  
  <p><strong>Option 2</strong> : The regular interface pattern. Same principle as option 1, but Activity would implement the interface. I feel a bit more coupling with this though.</p>
  
  <p><strong>Option 3</strong> : Messaging option, such as Otto or similar. ViewModel sends a Broadcast, Activity picks it up and launches what it has to. Only problem with this solution is that, by default, you should put the register/unregister of that Broadcast inside the ViewModel. So doesn't help.</p>
  
  <p><strong>Option 4</strong> : Having a big Routing class, somewhere, as singleton or similar, that could be called to dispatch relevant routing to any activity. Eventually via interface? So every activity (or a BaseActivity) would implement </p>
  
  <pre><code>IRouting { void requestLaunchActivity(ACTIVITY_B); }
  </code></pre>
  
  <p>This method just worries me a bit when your app starts having a lot of fragments/activities (because the Routing class would become humongous)</p>
  
  <p>So that's it. That's my question. How do you guys handle this?
  Do you go with an option that I didn't think of?
  What option do you consider the most relevant and why?
  What is the recommended Google approach?</p>
  
  <p>PS : Links that didn't get me anywhere 
  1 - <a href="https://stackoverflow.com/questions/46429511/android-viewmodel-call-activity-methods">Android ViewModel call Activity methods</a>
  2 - <a href="https://stackoverflow.com/questions/34389077/how-to-start-an-activity-from-a-plain-non-activity-java-class">How to start an activity from a plain non-activity java class?</a></p>