Hackernoon logoConcurrent Requests in Swift Using DispatchGroup, RxSwift and Combine by@altynberg

Concurrent Requests in Swift Using DispatchGroup, RxSwift and Combine

image
Altynbek Usenbekov Hacker Noon profile picture

@altynbergAltynbek Usenbekov

Software Developer

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:

image

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.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.