Issue
My code is like this.
GlobalScope.launch {
while (true) { // do something.. }
}
It's somewhat awkward. :(
Is this right way?
Solution
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
}
}
}
Answered By - Karunesh Palekar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.