Combine Tutorial Recap

Combine Tutorial | API Call using Future, DataTaskPublisher | Swift | Xcode

Estimated read time: 1:20

    Summary

    This tutorial introduces Apple’s Combine framework from the ground up and uses a network-calling example to show how it works in practice. The speaker explains what Combine is, why it matters, and how it fits into functional reactive programming through the publisher-subscriber model. He compares traditional completion-handler based API calls with Combine’s publisher-based approach, then walks through using Future and URLSession.DataTaskPublisher to fetch data asynchronously. Along the way, he covers key operators like tryMap, decode, receive(on:), and sink, plus the importance of storing subscriptions with AnyCancellable. The video also demonstrates how errors are handled and how the same pattern can be used to update a SwiftUI view model once data arrives. Overall, it’s a beginner-friendly overview of Combine with a practical API call example.

      Highlights

      • The video explains Combine as Apple’s framework for functional reactive programming, introduced at WWDC 2019 🚀
      • A radio transmission analogy is used to make the publisher-subscriber model easy to understand 📻
      • The API layer is refactored from completion handlers to a Future-based publisher flow 🛠️
      • The network response is filtered with tryMap, decoded into models, and delivered on the main thread for UI updates 🎯
      • The tutorial shows both success and failure paths by changing the URL and observing how Combine handles errors ⚠️

      Key Takeaways

      • Combine lets you write reactive, declarative code for async events like network calls and notifications 📡
      • The publisher-subscriber model is the core of Combine, with operators used to transform values along the way 🔁
      • Future is useful when you want to wrap an async operation and resolve it later with success or failure ✨
      • URLSession.DataTaskPublisher shows how Apple has extended existing APIs to work directly with Combine 🌐
      • sink creates the subscriber, and AnyCancellable is needed to keep subscriptions alive and manage memory 🧠

      Overview

      The video starts by framing Combine as Apple’s answer to reactive programming on iOS, especially useful for handling asynchronous work like web requests and notifications. It explains why developers might want to adopt it, mainly to avoid third-party dependencies such as RxSwift and RxCocoa while still getting a powerful reactive workflow. The speaker also notes that iOS 13 is the minimum target for Combine, which is one reason adoption has been slower.

        Next, the tutorial breaks down the main ideas behind Combine: publishers produce values over time, subscribers consume them, and operators transform the data in between. To make the concept easier to grasp, the speaker uses both a backend pub-sub analogy and a radio transmission example. This section gives a beginner-friendly mental model for understanding how data flows through Combine.

          Finally, the video moves into a Swift project that fetches flight data from a backend API. It shows how a traditional completion-handler approach can be replaced with a Future publisher, then layered with URLSession.DataTaskPublisher, tryMap, decode, receive(on:), and sink. The result is a clean pipeline that publishes data, handles errors, and updates the app’s view model when the response arrives.

            Chapters

            • 00:00 - 02:30: Introduction to Combine and Reactive Programming The presenter introduces the video topic: an overview of Apple’s Combine framework and reactive programming, with a plan to explain the concepts from scratch and later apply them to web service calls. He notes Combine was introduced at WWDC 2019 and is mainly available on iOS 13+, which has limited adoption but is becoming more relevant as older OS support drops.
            • 02:30 - 05:00: Publishers, Subscribers, and Operators Explained This chapter introduces Combine’s core roles using a radio analogy: publishers transmit values, subscribers listen for them, and the messages represent the data being passed.
            • 05:00 - 07:30: Comparing Closure-Based Networking to Combine This segment contrasts the traditional closure-based approach to web service calls with the Combine-based approach. In the older style, an API method accepts parameters plus a completion handler, and the callback fires once URLSession or another networking layer returns a response.
            • 07:30 - 10:30: Using Future and URLSession DataTaskPublisher This chapter explains using a Future to wrap an asynchronous web service call so a value can be promised and later delivered to a subscriber. The presenter describes Future’s output and failure types, and how a closure inside Future executes the work once the task completes or immediately fails if the URL is invalid.
            • 10:30 - 13:00: Transforming Responses with Combine Operators This chapter explains how Combine operators are chained inside a future-based networking method. A data task publisher is transformed with tryMap to validate the HTTP status code, then decode to convert response data into the desired model type, and receive(on: .main) to deliver values on the main thread.
            • 13:00 - 15:00: Subscribing with sink and Storing Cancellables This segment explains the flow of Combine in the networking example: `getData` returns a `Future` publisher, which internally uses a `dataTaskPublisher`, maps and decodes the response, and then completes the future’s promise with success or failure. It clarifies that the `sink` inside `getData` is for the inner `dataTaskPublisher`, while the `sink` in the `HomeViewModel` subscribes to the `Future` returned by `getData`.
            • 15:00 - 17:30: Updating the UI and Handling Success or Failure The speaker wraps up the discussion by noting that the same Combine patterns can be used anywhere values need to be processed over time, including other existing APIs that have been extended to work as publishers. They mention that instead of using data tasks directly, developers can use data task publishers, and then conclude the video with a brief sign-off encouraging viewers to subscribe and keep coding safely.

            Combine Tutorial | API Call using Future, DataTaskPublisher | Swift | Xcode Transcription

            • Segment 1: 00:00 - 02:30 hey guys welcome to my channel i code i am pallav and today we are going to talk about combined framework i have been receiving messages for covering the web service calls the networking part using combined so in this video we will not only discuss that particular networking part with the combine but we'll see combine in totality like what is combined what is publisher subscriber model why should we use it and i'll discuss the things assuming that you know nothing about combine so let's start apple introduced the combined framework in wpc 2019 and it has been more than two years but still not many applications are using it and the reason is minimum os version so if you want to use combine the minimum target version that your app should support should be ios 13 but now that ios 15 is going to be released this fall i think that it is the high time to get a hang off combine but eventually your apps will be removing the support of is 12 ios 11 and then combine is something that you should definitely look for so now the point comes that why would you use combine and the answer is that combine will let you remove the dependencies of external libraries like rx swift rx cocoa by providing you the flexibility of reactive programming so the same experience but without any third party in this video we will be using combined for making web service calls for fetching the list of the flights for fetching the details of these flights and the apis that i'll be using for these two things will be dummy apis they are hosted on my local server as you can see localhost 8080 and i have written these apis the backend in this swift so if you want to learn server side programming in swift here's the link now let's dive into
            • Segment 2: 00:00 - 02:30 combine so before jumping on to the code let's learn little bit about combine and the first thing is that what is combined combine is a framework similar to rx which allows you to write functional reactive code it provides you declarative apis i used the phrase functional reactive code what does that mean so in layman's language functional reactive programming is something that allows you to process values over time to process something that will be happening at some point in time some asynchronous stuff so you can relate it with network calls or you can relate it with the notifications because we don't know that at what time we will be receiving the notification be it push notification or be it local notification but we don't know that at what time that particular event will be taking place so anything where we want to process the values over time that can fall under the category of functional reactive programming and how does it work so it works on the principle of pub sub model that is publisher subscriber model so we have a publisher which produces the value and then we have subscribers one or more which consumes the value which is produced by the publisher and combine has introduced a third party
            • Segment 3: 02:30 - 05:00 in this which we call as operators so operators are nothing but they are a different kind of publishers which take the inputs which receives the value from some other publisher and then they produce some different value by performing some operations on it we'll see that in a minute pub sub models are generally implemented at back ends they have lot of technical components a lot of complexity and it is in fact a very good system design question but in layman terms you can relate it with how radio works so we have a transmitting tower from which the messages are transmitted and then we have the devices which tune into a particular frequency to listen to the messages that are being transmitted from that tar so this radio tar is the publisher these devices are the subscribers and these waves are the messages that are being published in terms of code publisher is a protocol and it declares that any entity that confirms to this protocol it can transmit a sequence of values over time now this protocol has two associated types that is one for output and the other one for failure so the output will be the type of value it can produce and the failure will be the type of error which can be encountered similar to publisher subscriber is also a protocol and it declares that any entity that confirms to this particular protocol that is subscriber it can receive input from publisher now similar to publisher it also has two associated types to make the publisher and subscriber work in sync the input type and the failure type of a subscriber must match the output type and the failure type of its corresponding
            • Segment 4: 02:30 - 05:00 publisher and the third entity that is introduced by combine is operators now operators are methods that are called on publishers and their return publishers so they are used for manipulating the values by changing them adding them or removing them and they can be chained together so you will see this in action when we will be making the web service calls once we receive the response from the server then we perform some operations on that particular response we either map it or we parse it and all these things will be done by operators so let's dive into the code now so in this dummy project i have used combine for handling the web service calls the network layer for fetching the list of these flights and the details of a specific flight when selected and let's go through the code now so this is the directory structure i'm having the network manager which is responsible for making the web service calls and for this home module what you are seeing here this is my home module and here i have this model of flight flight card view that is the view written in swift ui and then this home view model which is making the calls to the network layer and handling the business logic and all those kind of things so you don't worry about the code this project i have already hosted on github so you can
            • Segment 5: 05:00 - 07:30 clone it from there and i'll explain you each and every line of this code except the part which is related to the swift ui so i won't be explaining about the views that how those views are made and this observable object or this and then it published if you want me to explain them please put it in the comment but i think that paul has explained it brilliantly so let's start with our publisher part because that is the point from where the cycle begins but before that let's see that how we used to call the web services how we used to make an api call before the combine was introduced so this is how the method would have been i have used generics here well that's optional that is not related to combine in any way but what i want to show you here is this completion block we used to pass this completion handler which was returned once the response was received let it be by url session data task or lm of ir whatever you use but whenever you receive the response your completion handler was called and then you get the data so this is how the conventional way i mean this is how the web service calls were being done till the time combined was introduced and now that combine is there in the picture let's see that what changes are there because of the combine so the first thing that we need to understand is that many of the existing apis like url session notification center and all those have been extended to use the combined framework they have been extended as publishers and we will see that in a second so i have changed the signature of this method while you are comfortable with the first signature that we are passing an endpoint we are passing some id and all
            • Segment 6: 05:00 - 07:30 these are optional that depend on your use case but the important part was the completion handler that was being passed and in the second method you can see that we are not passing any completion handler instead we are getting some return which is future and we don't know that what this future is so that we will see in a minute but the crux is that some different type is being returned instead of a completion handler future is a kind of publisher so while learning about publishers i told you that publisher is a protocol which can be confirmed by any entity and future is one of them so combine is having many types of publisher and i'll put a link in the description from where you can read about different type of publishers what all are there and where you should use it but here we are using future and this future publisher basically works on the concept of promise so if you have worked with the languages like node.js or any kind of reactive programming then you would be knowing that what promise is but if you don't then let's just understand that promise is a block of code which gets executed when something happens so it's like that when x thing will be done in the future i promise you that i'll execute the y
            • Segment 7: 07:30 - 10:00 you can treat it like that it's not exactly like that but just to understand you can just take it as that when some particular x task will be done in the future asynchronously because we don't know when it will be executed so when some particular x task will be done in the future i promise you that this y block of code will be executed this task will be done so we are using future here for making our web service call and the color of this method will subscribe to this particular publisher so that it gets the value whenever they are published now let's see that how we have implemented it so the first thing that we are doing here is we are returning our publisher that is future and if you command click on future you will see that it has two types that that will be output and failure as we discussed yep output and failure because it is confirming to the protocol publisher as we discussed so it is having two types and i have mentioned this t type rather array of t type that will be my output value this is because of i have used generics here but it can be any other type on which you are using your feature publisher and then the error now we are having this closure and in the closure we are making the web service call so that web service call is being made by this url session data task publisher now this is something else but let's first go through these lines what's happening here so here i'm having a guard statement to ensure that my url is a valid url and if it is not then i'm passing this failure from the promise so promise is something that will get executed once the x task is done
            • Segment 8: 07:30 - 10:00 but because my url is invalid i am not able to proceed with that x task so it eventually means that it has ended as soon as it began so that's why i am passing this failure from the promise and if it is not then i am making the web service call using this url session dot shared dot data task publisher now this data task publisher is also a publisher as i mentioned that some of the existing apis have been extended to use the combined framework and url session is one from them so it is having this data task publisher which will publish the data after making the web service call after using the data task so we are passing our url here and of course we can pass url request also if you want to customize your url request you want to change the methods and all that so if you go here you will see that this is the method where the url is being received as the parameter and we also have the same method for url request so i'm passing my url here and once this particular publisher will publish the data then i'm going to do something on it and what i'm doing here is i'm using the
            • Segment 9: 10:00 - 12:30 operators so try map is one of the operators and if you remember operators are nothing but methods which are called on publishers and they return the publishers so triumph is also a kind of publisher but we should treat it as an operator because it is being called on the publisher that is data task publisher so in this try map i am mapping my response basically i have used this pattern matching operator to see if my status code is lying in the range of 200 and 299 and if i have received the response so this is my try map operator is doing and i also mentioned that operators can be chained together so this is the second operator that i have chained with this try map that is decode so i am now decoding the data that is received for the type t that we used to do in our closures and then there's this third operator that is receive and i'm saying that i want to receive the response on the main thread so we can mention it here and this is all optional if you don't want to do it you can completely skip it and then you can use the dispatch queue.main.async and all those kind of things at the point where you are receiving the data so i have used it here and this is the important thing that is sync now whenever we use this sync we are creating a subscriber so if you go in the documentation of this sync method you will see that it has two values rather two parameters i should say one is the receive completion and the second is receive value the receive completion will tell us that whether a particular operation has been completed successfully or not it was a success or it was a failure and the second
            • Segment 10: 10:00 - 12:30 closure that is received value it will give us the value that has been received so through this sync method we can create the subscriber so if anything goes wrong then i'm passing the failure to the promise with the specific error whatever the error has been encountered and if all goes well then i'm passing the success to my promise so this is about the sync so through sync we can create the subscribers that is fine and then comes this dot store now this is also one of the important concepts why are we using this restore method here what is the use of it so whenever we create the subscriber that subscriber remains in the memory it is used whenever it is required so whenever a publisher will be publishing the value that particular subscriber will be used but then what about the d initialization part so for that we need to store its reference somewhere so that it can be removed from the memory whenever required and for that we are having this set here and this set will be having the elements of type any cancelable so that is why this dot store method is
            • Segment 11: 12:30 - 15:00 being used here so let's quickly go through the code once again we are returning a future publisher from this method get data and inside the future publisher we are using our data task publisher our data task publisher is returning us the values those values are being mapped using the operators like tri-map we are using decode operator over there receive and then through the sync we are subscribing to this particular publisher and we are passing success and failure to our promise as per the conditions so this promise part is specific to the future publisher but all other concepts like publishers subscriber operators they are common to all the publishers so if you go for using any other publisher apart from future those concepts will remain same now let's see that how this get data function is being called and how that data is being used so this is being called from this home view model that is network manager.share.getdata and as you can see we are having sync here too so don't get confused the sync that we are having here is for this data task publisher basically we are having this subscriber for this particular publisher that is our data task publisher and the sync that we are having in our home view model that is for our future publisher that is being returned from our get data method so the same concept is being used we are returning a future publisher from here that is being handled in our home view model the sink is there and the data task publisher that is being used inside the get data method we are having a sync for it there itself so this is how when getdata method will return
            • Segment 12: 12:30 - 15:00 the publisher or rather when the subscriber will receive the values we are setting the flights data to our flights property in our home view model and accordingly our view will be updated so if i give it a run you will see that how the call is being made and how the data is being set on the view now let me try changing the url so that we can check for the failure case too and in the get data method my bad what if i change this to something else so you see that we have not received the data because i changed the url so this was the crux that how you can use combine i chose web service calls as the use case but you can use combine at
            • Segment 13: 15:00 - 17:30 other places also so wherever you need to process values over time you can use combine there and just go through the existing apis those have been extended as publishers so that you can use them instead of using data tasks you can use data task publisher just like that so that's pretty much for this video a new video comes out every weekend so you can consider subscribing to the channel let's write better code together happy coding and stay safe