Home > Net >  Kotlin - Infinite but cancellable timer
Kotlin - Infinite but cancellable timer

Time:12-27

Currently have this approach

repeat(10000) { i -> delay(1000L) }

But how can I have a repeating execution with the following requirements.

  1. Not recursive.
  2. Infinite time/execution but can be cancel using its public method.

CodePudding user response:

You can create a new Job for the repeating task and cancel the job when you want to stop.

private var job: Job? = null

fun startInfiniteExecution() {
    job = scope.launch {
        while(true) {
            doYourTask()
            delay(1_000)
        }
    }
}

fun cancelTask() {
    job?.cancel()
}

CodePudding user response:

Using Kotlin Coroutines you can create like this.

class MainActivity : AppCompatActivity(),CoroutineScope by MainScope() {
    
        lateinit var binding: ActivityMainBinding
        private var job: Job? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding= ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
            startInfiniteExecution()
        }
    
        fun startInfiniteExecution() {
            job = launch {
                while(true) {
                    doYourTask()
                    delay(1_000)
                }
            }
        }
    
        fun cancelTask() {
            job?.cancel()
        }
    
    }
}
  • Related