Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best practice make infinite loop in Kotlin coroutine?

My code is like this.

GlobalScope.launch {
            while (true) { // do something.. } 
}

It's somewhat awkward. :(

Is this right way?

like image 561
Taz Avatar asked Jan 21 '26 22:01

Taz


1 Answers

You should not use GlobalScope for creating infinite loops . Since one of your tag mentions android , assuming you are writing program for the same , it is highly recommended that you use LifycycleScope / ViewModelScope when you are in Fragment-Activity / ViewModel respectively .

It is easy to accidentally create resource or memory leaks when GlobalScope is used. But since these scopes(lifecycleScope / viewModelScope) are lifecycle-aware , they will get automatically cancelled when the particular class(fragment/viewModel) is killed . Either you use one of the prebuilt-scope or create your own scope handling the lifecycle with viewLifecycleScope instead of using the GlobalScope for creating an infinite loop . You can make use of viewModelScope in the following way :

fun runForever() {
    // start a new coroutine in the ViewModel
    viewModelScope.launch {
        // cancelled when the ViewModel is cleared
        while(true) {
            delay(1_000)
            // do something every second
        }
    }
}
like image 114
Karunesh Palekar Avatar answered Jan 23 '26 21:01

Karunesh Palekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!