1

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)
  • ....?
macnixde
  • 213
  • 1
  • 9
  • I think this question is a little opinion-based and it also depends on a specific case. I personally think if the service is expected to be a part of another service or execution flow, it clearly has its parent, then it should receive `CoroutineScope` in its constructor or factory function. No need to call `cancel()`/`close()` manually - this is exactly what we try to avoid by using structured concurrency. If the service is more standalone and has many consumers then it may be hard to find a clear parent/owner for it, but still, the main coroutine may be a good candidate for this. – broot Nov 07 '22 at 10:14
  • 1
    Also, remember structured concurrency is not only about cancellations. What if a coroutine in your service crashes, making the whole service not functional? In many cases that means other services won't know about this, they will still try to use your service, the application may get stuck somewhere and be hard to debug. – broot Nov 07 '22 at 10:34
  • It is an opinion-based question, which has no right answer. However, in some redux-based architecture patterns structured concurrency is used by creating a global coroutine scope of the application, which lately launches child scopes for different features/views/components. – Steyrix Nov 07 '22 at 11:07

0 Answers0