Hey! In my web service I have a requirement to ret...
# coroutines
j
Hey! In my web service I have a requirement to return a response on the request thread pretty fast. So I am using
GlobalScope.launch
to send fire-and-forget HTTP requests to other services. I don't like the
GlobalScope.launch
idea and trying to thinking of other solutions. If I would have been in Clojure I think I would have created a global go-loop to handle the fire-and-forget requests and have a channel to communicate with that go-loop. Could that been done in Kotlin? Is that a good approach for concurrent fire-and-forget stuff or are there better ways of doing it?
z
Inject a “global” scope into your service and use that instead. In production, that can be GlobalScope, but in tests you can use a cancellable scope to ensure test isolation.
j
Thank you for the reply @Zach Klippenstein (he/him) [MOD]! Just to make it clear. For example in a Spring world I can create a "global" scope that I can dependency inject into controllers. In production I can inject a GlobalScope, but in tests that could be some other type of scope that I can manage more?
f
You could use a buffered channel for the fire and forgot principle. Then collect and process the values with multiple processors using fan-out principle https://kotlinlang.org/docs/channels.html#fan-out
j
Thank you for the reply @Francis Reynders! Maybe my mental model is wrong. But isn't it fan-in in this case? A single shared channel that can be injected anywhere? That channel is then a queue for processing the fire-and-forget requests.
f
Actually both I would suspect. Fan-in would be the webservice handler invocations sending to the channel. Fan-out would be the processors processing the data.
j
I see. Fan-out in that case would then give me concurrent processing of the fire-and-forget requests, right?
f
yes, see the kotlin docs about it. You can decide the number of processors and the CoroutineScope in which they run. There was also a great talk about it on youtube by Roman Elizarov if I remember correctly, will see if I can locate it.

https://www.youtube.com/watch?v=a3agLJQ6vt8

j
Thank you for the resources. Will dig further 😄