If we talk about modern iOS applications that takes a lot of CPU-intensive tasks. Most operations like network and media file computation must beasynchronousso that the app remains responsive to users. The normal approach to asynchronous programming in Swift iscallback-basedapproach. However, the following caveats apply —
Async programming with callbacks is hard to manage.
It violates the inversion of control.
Futures and promises have none of these drawbacks.
Let's understand more , All of us have encountered situations where we’ve had to write code like this:
photoManager.getAccess { accessResult inswitch accessResult {
case .success:
photoManager.selectPhoto { selectionResult inswitch selectionResult {
case .success:
photoManager.uploadPhoto { uploadResult in...
}
case .failure:
...
}
}
case .failure:
photoManager.showAlert {
photoManager.retry {
...
}
}
}
}
This is commonly referred to as thePyramid of Doom— a code structure that resembles an arrowhead and is considered an anti-pattern resulting from multiple nested closures or structures such as nested conditions or switch statements.
In this material, we will explore how to eliminate nested closures using Combine and thus simplify the code while enhancing its readability and maintainability. Let’s explore how it can be valuable for handling asynchronous tasks, such as networking.
Here is a typical example of running several network requests in sequence: