How to pass the CoroutineScope to composed objects in Kotlin (Structured Concurrency)

242 views Asked by At

I have a Kotlin application main class which provides a CoroutineScope. The main class creates various instances of other classes (composition), all of which should use the scope from the main class in order to implement proper structured concurrently patterns and enable a clean cancellation/shutdown..

NB: some of the child classes need to launch some background monitoring tasks in their initializer. So they need to have the coroutineScope available at class level.

What is the best and most idiomatic way to pass the scope to the component classes?

  • pass the scope to the child class as a constructor argument?
  • have each class inherit from CoroutineScope (having its own lifetime) and cancel that scope from the main class (risk of forgetting to cancel)
  • creating builder methods for the child classes, which would call the monitoring functions with the parent scope (not sure how this would be implemented)
  • ....?
0

There are 0 answers