title: How to stop coroutines?
body: <p>I'm trying to have a counter using coroutines and not sure if this is the right way to ensure the job and coroutine ends before calling <code>coroutineScope?.cancel()</code></p>
  <p>Is this the correct way and is there a simpler implementation for the same?</p>
  <pre><code>class Counter {
      private var coroutineScope: CoroutineScope? = null
      private var job: Job? = null
      private var counter = 0
      
      fun startJob() {
          stopJob() 
          coroutineScope = CoroutineScope(Dispatchers.Main)
          job = coroutineScope?.launch {
              while (isActive) {
                  yield()
                  counter++
                  delay(2000)
                  say(&quot;counter: &quot;, &quot;$counter&quot;)
              }
          }
      }
  
      fun stopJob() {
          coroutineScope?.launch {
              if (job.isActive) {
                  job?.cancelAndJoin()
                  job = null
              }
          }
          coroutineScope?.cancel()
          coroutineScope = null
          counter = 0
      }
  
      companion object {
          @JvmStatic
          fun main(args: Array&lt;String&gt;) {
              println(Test())
          }
      }
  }
  </code></pre>