Matteo Mirk
09/29/2022, 7:37 AMalso { }
), to send an event before calling a service. We came up with this, but I think it’s ugly and was wondering if it could be simplified:
override suspend fun validateCart(request: ValidateCartRequest): ValidateCartResponse {
supervisorScope {
launch(Dispatchers.Unconfined) {
domainEventsPublisher.publishCartValidationSubmitted(request.cartId)
}
}
return super.validateCart(request).also { response ->
supervisorScope {
launch(Dispatchers.Unconfined) {
if (response.isValid) domainEventsPublisher.publishCartValidationSucceeded(response)
}
}
}
}
can i wrap everything in a single supervisorScope? Would it be equivalent to this code?Sam
09/29/2022, 7:44 AMsupervisorScope
? Unless I’m missing something,
supervisorScope { launch { doThing() } }
is pretty much equivalent to
doThing()
(aside from error handling, which you can do with try/catch)Matteo Mirk
09/29/2022, 7:50 AMMatteo Mirk
09/29/2022, 7:51 AMpublish()
super.validateCart()
they would be executed sequentially, in a blocking waySam
09/29/2022, 7:53 AMsupervisorScope
will always wait for its child jobs to complete. So a supervisor scope with a single child job is very similar in behaviour to no supervisor scope at all.Sam
09/29/2022, 8:00 AMsuspend
functions run some work and return when it’s complete
• CoroutineScope
extension functions launch background work and return immediately
The library deliberately makes it very difficult for you to make a suspend
function that launches background work and returns before it’s complete.Matteo Mirk
09/29/2022, 8:01 AMMatteo Mirk
09/29/2022, 8:05 AMSam
09/29/2022, 8:07 AMsupervisorScope
does stop exceptions from propagating, but if that’s all you need it for, it’s much simpler to use try/catchSam
09/29/2022, 8:09 AMChannel
in the domainEventsPublisher
• Have the domainEventsPublisher
launch its own long-running coroutine that reads messages from the channel and uses them to publish events
• Then all the validateCart
function needs to do is send a message to the channel; it doesn’t need to wait for the domainEventsPublisher
to handle the message.
(Actually this new coroutine + channel could live anywhere, they don’t necessarily have to be inside the domainEventsPublisher
)Sam
09/29/2022, 8:10 AMvalidateCart
function signature, a different option would be to add a CoroutineScope
as a parameter/receiver and use that when you need to launch background tasks, but that’s not such a clean design IMOMatteo Mirk
09/29/2022, 10:00 AM