An API design question. If I am designing some ki...
# coroutines
d
An API design question. If I am designing some kind of Service which has its own coroutine scope tied to its lifecycle, and it maybe has a few `Flow`s in the interface with some async events, and then it has methods for clients which query some info, for example:
isSubsystemFooInitialized(): Boolean
If these "query-like" methods go through a DB and they need to be non-blocking, I'm tempted to make them
suspend
, but then this has the effect that client can call them in whatever corotuine scope they like, outside of Service's lifecycle (which may or may not be a problem), and the API of the service becomes not uniform: it partly manages its operations in its own scope, but these "suspend" parts are kinda "leaking". I could turn them into "reactive" properties
Flow<Boolean>
but this feels a bit like an overkill. Maybe someone has thoughts on how to approach this?
s
In principle you could do something like this:
Copy code
suspend fun foo() {
  myScope.async { getFoo() }.await()
}
But it's probably worth thinking closely about what specific kind of "leaking" you're worried about. Do you have any specific concerns about problems that would be caused by having two different coroutine scopes interacting with the service at the same time?
d
Not really, usually these non-blocking calls are a simple DB reads, so it wouldn't pose any problem, but somehow I feel uneasy about polluting an API surface which is usually suspend-free (service completely encapsulates the coroutine scope and
launch
-es) with
suspend
-functions. These functions also feel like they are a part of the service, because they are related to what it does, so it makes sense to keep them as methods. But maybe it's still a sign that they belong elsewhere 🤔