DEV Community

Discussion on: Basic Concurrency in Ruby. Really Basic.

Collapse
 
chrisfrank profile image
chrisfrank • Edited

Brian,

Thanks for taking the time to bring clear documentation into the ruby community. For writing complex concurrent code, concurrent-ruby is an excellent library--but for simple concurrency like API calls, it may be overkill. Ruby actually has solid concurrency built into its standard library, via its Thread class.

To make multiple API calls simultaneously with threads, following your example above, you'd do something like this:

call_1 = Thread.new { some_api_all }
call_2 = Thread.new { some_other_api_all }

response_1 = call_1.value
response_2 = call_2.value

Here's the same idea, with less repetition:

data = ["https://some_api",  "https://another_api"].map { |url|
  Thread.new { SomeHttpLibrary.get(url) }
}.map { |thread| thread.value }
# data is an array of API responses [response1, response2]

Check this blog post from Thoughtbot for more on how threads work. I have no affiliation with Thoughtbot, I just think their blog is a great resource for rubyists of all experience levels.

Collapse
 
briankephart profile image
Brian Kephart

Thanks for the reply, and for adding another (better!) approach.

I used concurrent-ruby because it was already in my project as a Rails 5 dependency, so when I started my search it seemed like the obvious tool for the job. Now it turns out what I needed was in the standard library all along, go figure.