https://kotlinlang.org logo
#getting-started
Title
# getting-started
z

Zakhar

10/22/2023, 2:46 PM
Hey guys what do you think what way is better to running an infinite task? this:
Copy code
CoroutineScope(Dispatchers.Default).launch { updateRooms() }

private suspend fun updateRooms() {
    mutex.withLock { for (room in rooms) room.update() }
    delay(delay)
    updateRooms()
}
or this:
Copy code
CoroutineScope(Dispatchers.Default).launch {
    while (true) {
        mutex.withLock { for (room in rooms) room.update() }
        delay(delay)
    }
}
The first one uses a recursion. Should i care about stack overflow in this case?
s

Sam

10/22/2023, 2:53 PM
Either approach is fine -- just add
tailrec
to make the first one work without stack overflow
j

Joffrey

10/22/2023, 2:55 PM
Yes you should care. The stack overflow can be solved with
tailrec
as Sam said, but that's not the most important. You should rather care about the readability of your code. Using recursion here is weird, because the behaviour you want for your system is an infinite loop by definition. Some problems are inherently recursive, like divide-and-conquer algorithms, and using recursion in the code to solve those problems makes sense because it aligns with how you think about them. You usually start with the recursive code because it makes sense and is readable, and then maybe you switch to iterative code (if possible) when/if you need to improve the memory footprint at the expense of readability. But that is not your case here. You don't have a recursive problem. You have a loop, and you choose to express it recursively for no apparent reason. It doesn't match how you think about the problem, so it's not nice to read it this way.
7
c

Chris Fillmore

10/22/2023, 4:47 PM
Also I think
while (isActive)
is suitable here
j

Joffrey

10/22/2023, 4:55 PM
What's the use of it? There are delays and suspend calls in the loop, so cancellation will be handled anyway
c

Chris Fillmore

10/22/2023, 6:23 PM
Indeed 👍 seems I didn’t look that closely
v

Vishnu Shrikar

10/23/2023, 12:12 AM
From the code you have posted, it looks like a constant update, this may be totally fine in your use case but it may be good to consider other patterns or libraries for these types of workflows. I would also like to add that while tail recursion makes this point moot, I always prefer iterative solutions. Every recursive problem has an iterative counterpart.
r

Ronny Bräunlich

10/23/2023, 4:53 AM
How do you intend to start/call this code?