Jojo01
Jojo01

Reputation: 1289

Kotlin - Coroutines with loops

So, I have a simple algorithm that follows a tree structure in this manner:

Simple tree

Each time it moves from one node to the next, it propagates attributes of the previous node to the next node and so on, to simulate the effects that the nodes have on each other.

Sometimes a node may be connected to more than one node.

With my current implementation the algorithm follows each split path to the end before completing the rest of the tree:

Split tree

This is sub-optimal, as all the other branches have to wait for the algorithm to finish, which is a lot of wasted time, especially if the tree is very large.

Ideally I would want each split to spawn a new thread, so that all the routes will be explored in parallel.

I am currently new to Kotlin's coroutines, so please bear with me if this seems stupid.

Currently, I am thinking of implementing this in the following way using Kotlin's coroutines (Note: This is approximate code):

suspend fun propagate(startFromNode: Node) {
   coroutineScope {
      while (true) {
        //Do propagation
        if (split) {
           launch {
              propagate(splitNode)
           }
        }
        if (atEndOfPath) {
           break
        }
      }
   }
}

I am unsure how Kotlin handles a situation where coroutines can also spawn new coroutines.

If one coroutine throws an exception for some reason, will all the other coroutines that originate from this main coroutine scope be canceled, including the coroutines that have been started by other coroutines?

Also, I would like to achieve this using a recursive function if possible, but it doesn't seem like there is an easy way to do that with coroutines.

Thanks.

Upvotes: 3

Views: 6015

Answers (1)

Dominic Fischer
Dominic Fischer

Reputation: 1849

You can find out more details about this if read about structured concurrency. But to answer your immediate questions.

Your implementation looks like what I would've written myself (and probably most people). Recursion seems to be the way to go here and is possible as you've done it.

Yes! Every call to propagate will wait for it's children coroutines to finish before returning, so when one of the children throws an exception the parent and siblings are cancelled (exceptionally). coroutineScope would then throw the exception, which mostly cancels the entire coroutine stack.

Upvotes: 2

Related Questions