My code is like this.
GlobalScope.launch {
while (true) { // do something.. }
}
It's somewhat awkward. :(
Is this right way?
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With