1

I am new to using co routines .... I am trying something like this

  • Start a thread(using co routines) on resume() of activity
  • Run the thread indifinately
  • Set textview every 5 seconds
  • Stop onPause() of activity life cycle
Devrath
  • 42,072
  • 54
  • 195
  • 297

1 Answers1

3

You can do this

private var job: Job? = null

override fun onStart() {
    super.onStart()
    job = lifecycleScope.launch {
        while (true) {
            /* do work */
            delay(5000L)
        }
    }
}

override fun onStop() {
    job?.cancel()
    job = null
    super.onStop()
}
Francesc
  • 25,014
  • 10
  • 66
  • 84
  • `lifecycleScope` comes from the [androidx.lifecycle:lifecycle-runtime-ktx:2.2.0+](https://developer.android.com/topic/libraries/architecture/coroutines) dependency. A nice addition so you don't have to manage your own scope. Thanks for that! Though in this case the job is cancelled anyway before the scope would but still – RobCo Mar 27 '20 at 15:40