https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

ribesg

10/12/2020, 12:37 PM
Would you use
isActive
instead of
true
as an infinite
while
loop condition in a coroutine if the loop calls suspending functions (
delay
, among others)? I don’t think it changes anything, but maybe it makes things more clear to the reader? Thoughts?
l

louiscad

10/12/2020, 12:38 PM
I use a function named
repeatWhileActive { }
for these purposes: https://github.com/LouisCAD/Splitties/tree/main/modules/coroutines#cancellable-infinite-loops
r

ribesg

10/12/2020, 12:39 PM
Isn’t cancellation checked on each suspending call already?
l

louiscad

10/12/2020, 12:41 PM
Each cancellable suspending call, yes, but I prefer to be safe in case after edits, they all go through a fast path that doesn't check for cancellation, or in case all exceptions are eaten. Plus I think
repeatWhileActive
is more descriptive than
while (true)
plus implicit exit/cancellation conditions.
BTW, here's the implementation in case one is interested but doesn't want to use the library itself or is curious: https://github.com/LouisCAD/Splitties/blob/1936c6c7e445c048077d8b4b7bb1c13b99e0ca0a/modules/coroutines/src/commonMain/kotlin/splitties/coroutines/ScopeLoops.kt#L19-L24
3 Views