title: Wait for coroutine to finish to handle user click
body: <p>I'm making a system of "sessions" where the user can launch, finish and view his session.<br>
  The user go through a first fragment to create his session and then go into a fragment "in session".<br>
  If he return to the main menu before finishing his session, I want him to go directly to "in session" without going through the "new session" fragment.</p>
  
  <p>All session data are stored into a local database and I use Kotlin coroutines to fetch data from the db (see code example below)</p>
  
  <blockquote>
    <p>It's my first time using coroutine, and I will admit it's a bit fuzzy
    for me, all the help is welcome</p>
  </blockquote>
  
  <p><strong>The problem is</strong> that when the user press the bouton to navigate, the coroutine finish <strong>after</strong> the verification to see if there is a current session, that lead to verify a null object or the previous session of the current session, and so navigate to a the "new session" fragment</p>
  
  <blockquote>
    <p>What I need is a way to wait for the coroutine to finish and then
    handle the button click</p>
  </blockquote>
  
  <p>All the code wrote here is <strong>contain inside inside the viewModel</strong>.<br>
  This is how I setup the Job/Scope</p>
  
  <pre><code>private var viewModelJob = Job()
  private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
  </code></pre>
  
  <p>And this is how I launch the coroutine:</p>
  
  <pre><code>private fun initializeLastSession() {
      uiScope.launch {
      lastSession.value = getLastSessionFromDatabase()
      }
  }
  
  private suspend fun getLastSessionFromDatabase(): Session? {
      return withContext(Dispatchers.IO) {
          var session = database.getLastSession()
          session
      }
  }
  </code></pre>
  
  <p>The verification is made inside this function</p>
  
  <pre><code>fun isSessionActive(): Boolean {
  //Simplified
      if (lastSession.value = null) {
          return false
      } else if (...) {
          return true
      } else {
          return false
      }
  </code></pre>
  
  <p>This last function "isSessionActive" is called from an <strong>if</strong> statement from the fragment itlsef, when the user press the navigation button.<br>
  If it's true then it navigate to "InSession", else in "newSession"</p>
  
  <p>I've seen multiple way of waiting for a coroutine to finish but none match the way I launch it, and even less have a solution that has worked for me.</p>