Concurrent Requests in Swift Using DispatchGroup, RxSwift and Combine

Written by altynberg | Published 2021/02/10
Tech Story Tags: swift | ios-app-development | ios-development | requests | swiftprogramming | rxswift | programming | coding

TLDR 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.via the TL;DR App

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.

Written by altynberg | Software Engineer
Published by HackerNoon on 2021/02/10