title: Implement Redux with Android Observer/Livedata/Coroutine/Kotlin
body: <p>Consider the Android app architecture that is recommended by Google: <a href="https://developer.android.com/jetpack/docs/guide" rel="nofollow noreferrer">https://developer.android.com/jetpack/docs/guide</a><br>
  This architecture is based on ViewModels and Observables, therefore I would categorize it as "Model-View-ViewModel" (MVVM) architecture.</p>
  
  <p>This is quite different to React-Redux. Whereas the Android architecture encourages bi-directional dataflows between Views and ViewModels, Redux enforces a uni-directional dataflow in a circle.
  Moreover, the Android architecture keeps state in several ViewModels, whereas Redux enforces a centralized store.</p>
  
  <p>Now my question is how to implement Redux with native Android libraries.
  My first attempt would be:</p>
  
  <ul>
  <li>Implement a centralized store as a Kotlin Singleton object.</li>
  <li>The store provides a <code>sendAction</code>-method that takes an action, puts it in a queue and then returns quickly.</li>
  <li>Actions are pure Kotlin data classes because they should not contain any logic.</li>
  <li>Within the store, implement a Kotlin-Coroutine that picks up actions from the queue and dispatches them with a huge switch-statement.</li>
  <li>Use a Room-database + some ephemeral state as a model. In particular, the ephemeral state controls which Fragment/Dialog is shown at any given time. </li>
  <li>Ensure that the state is only mutated by the Coroutine.</li>
  <li>Use observable livedata (<code>androidx.lifecycle.LiveData</code>) to re-render the UI whenever the Room-database or the ephemeral state changes.</li>
  <li>Since observables are not enough to control an Android UI, I would also need a function that compares the current fragment/activity with the expected state, and e.g. trigger a FragmentManager transaction if a deviation is detected.</li>
  </ul>
  
  <p>However, a few points are not clear:</p>
  
  <ul>
  <li><p>How to keep activity/fragments in sync with the global state? Perhaps I would use a single activity and replace fragments as needed, depending on the current state of the store.</p></li>
  <li><p>How can I implement both async + sequential action dispatching? Perhaps I would implement a single Kotlin-Coroutine that picks up incoming actions from the queue and dispatches them straight on the UI thread.</p></li>
  <li><p>How can we ensure that the entire UI is re-rendered before new actions are dispatched? Perhaps I would stall the dispatching coroutine until there are no more other runnables in the queue of the UI thread?</p></li>
  </ul>