paint-brush
Concurrent Requests in Swift Using DispatchGroup, RxSwift and Combineby@altynberg
3,737 reads
3,737 reads

Concurrent Requests in Swift Using DispatchGroup, RxSwift and Combine

by Altynbek UsenbekovFebruary 10th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Concurrent Requests in Swift Using DispatchGroup, RxSwift and Combine can be done in three ways in Swift. I’ve created a simple project with all three methods. The source code is available here on GitHub. The project is based on a simple simple project that takes a simple movie ID and gives a movie object: getMovie. We can call the getMovie method for given IDs in parallel and get notified when we got all of the responses using the DispatchGroup. When we got the response we have to call a group.leave() method, and when all entered blocks leave the group we will be notified.
featured image - Concurrent Requests in Swift Using DispatchGroup, RxSwift and Combine
Altynbek Usenbekov HackerNoon profile picture

Sometimes we need to make multiple asynchronous requests and get the result when all requests have finished. In this post, I’ll show how to do this in three ways in Swift:

  1. with DispatchGroup
  2. with RxSwift
  3. with Combine

I think in a real situation you must think twice before making multiple requests like in this example. Because it can consume more energy, drain the battery faster, and it is better overall if we can make it with a single request.

Let’s say we have a simple method that takes a movie ID and gives a movie object:

And let’s say we have a list of movie IDs and we want to get a list of movie objects of these IDs. We can call the getMovie method for given IDs in parallel and get notified when we got all of the responses using the DispatchGroup:

Here we used the group.enter() method to let the DispatchGroup know a new block entered the group. When we got the response we have to call a group.leave() method, and when all entered blocks leave the group we will be notified.

In the example below, If we've made requests one after another, the total time would be more than six seconds. But we were notified in less than two seconds because the movies loaded in parallel:

Let’s see how can we do it using RxSwift:

We can also achieve this using the Combine:

I’ve created a simple project with all three methods. The source code is available here on GitHub.