title: How should I restart/retry Kotlin coroutine after exception in Android
body: <p>I am really happy that I switched my long running tasks, which constantly produce <strong>results to UI thread</strong> to <strong>coroutines</strong>. It improved performance and decreased memory usage by 3 times and all memory leaks disappeared compared to AsyncTask or regular Threads in Android. </p>
  
  <p>The only problem remains is that, I don't know how should I restart my long running operation after exception <strong>has occurred at some time</strong>...</p>
  
  <p>I feel I did not understand exception handling in coroutines at all after reading tons of article. Let me know how can I achieve desired behaviour.</p>
  
  <ol>
  <li>I  have coroutine scope in fragment(will move to VM in near future).</li>
  </ol>
  
  <p>&#8203;</p>
  
  <pre><code>    lateinit var initEngineJob: Job
      override val coroutineContext: CoroutineContext
          get() = initEngineJob + Dispatchers.Main
  </code></pre>
  
  <p>&#x200B;</p>
  
  <ol start="2">
  <li>Long running task with async/await.</li>
  </ol>
  
  <p>&#x200B;</p>
  
  <pre><code>fun initWorkEngineCoroutine()
      {
          launch {
  
              while(true) {
                  val deferred = async(Dispatchers.Default) {
                      getResultsFromEngine()
                  }
                      val result = deferred.await()
                      if (result != null) {
                      //UI thread
                          draw!!.showResult(result)
                      }
                  }
              }
  
          }
  
  fun getResultsFromEngine() :Result? {
             result = // some results from native c++ engine, which throws exception at some times
             return result
     }
  </code></pre>
  
  <p>i don't know where should I put try catch. I tried to surround deferred.await() with try catch, but I could <strong>not call same method in catch block</strong> to retry long running task. I tried <em>SupervisorJob</em>(), but no success either. I still could not call <strong>initWorkEngineCoroutine() again</strong> and <strong>start new coroutine</strong>...  </p>
  
  <p>Help to solve this issue finally :)</p>