iOS 13 Swift Tutorial: Combine Framework - A Practical Introduction with UIKit

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome to another very exciting tutorial today I'd like to help you understand the combined framework and show you how you can use it in a new I kid app we're going to build some examples that use the combined framework for different purposes like connecting you switch in a button and sending some messages within our app before we do that you're going to learn what the combined framework is and how it works also with some basic examples in a playground and if that sounds good make sure to hit that like button and subscribe to not miss any future videos so now let's get started so before we work with the combined framework in practice let's see what it is and how it works in theory so the combined framework is a declarative Swift API for processing values over time we're going to focus on the processing values over time in a second let's first of all have a look at what declarative really means so to better understand what the clarity means and what declarative coding is let's compare it to imperative programming these are actually two mental models imperative programming is much more of a how something works and a mental model that is much closer to how a computer works and the clarity of programming is much more tailored to how humans think and we're describing what we actually want let's also have another example maybe for a recipe for mashed potatoes so in an imperative way what we would do is to give a very detailed instruction of how mashed potatoes are made so first we peel the potatoes then we cook the potatoes then we mash the potatoes and then we add butter and maybe also nutmeg so this is the imperative way of doing things so in a declarative way what we would do is maybe asking a chef please make mashed potatoes and the chef says ok here you are and in other terms that means that rather than potentially implementing multiple delegate callbacks or completion and the closures you can create a single processing chain for a given event source to clear this up let's say you used your cool radio with a display to subscribe to a great radio Weather Service and there is naturally in this amazing publisher that delivers great weather data so what you really need to do is to attach your radio the subscriber to the publisher you are interested in and your subscriber has to tell the publisher that it wants to receive values in our case weather data over time very important to remember here is that the publisher only emits values when explicitly requested to do so by a subscriber like your radio once the subscriber receives an element it can act on it in our case for example display the weather data in its discipline but there is a problem it doesn't really fit into the display that's not really cool but fortunately there are tools that can help us modify data that st. just remove this icon and our temperature value now fits nicely into the screen of our radio now in terms of the combined framework tools like this hammer could be called operators and they can act on the values receive from upstream publishers and republish them in a form that fits your needs so publishers subscribers and operators these are the building blocks of combine and to better understand these building blocks or key concepts let's have a look at them in detail one more time so first of all the publisher the publisher defines how values and errors are produced there are strengths of value types and they allow registration of one subscriber the subscriber receives values and potentially a completion their reference types and an operator also adopts publisher it describes the behavior for changing values and they subscribe to a publisher which is called an upstream they send results down to a subscriber just called downstream and they're also value types like a publisher now the relationship between a publisher and a subscriber is something that we need to discuss a little more detail so we have to look at the input and output types as you can see in this example or in the definition of the subscriber and publisher protocols we have for the subscriber an input type for the publisher and output type and for both of them to communicate we need to make sure that the input type and output type really match same is true for the failure type so in order to make this happen we can use operators we're going to see that in practice in a second but let's first of all have a look at some special subscribers that really take this burden from us because there are two special subscribers the first one is called sync sync takes two closures the first closure executes when it receives subscribers completion which is an enumeration that indicates whether the publisher finished normally or failed with an error the second closure executes when it receives an element from the publisher for example you can use the sync subscriber to log when the publisher completes and each time it receives an element the second special subscriber is called a sign and it immediately assigns every element it receives to a property of a given object using a key path to indicate the property both the sync and assigned subscribers request an unlimited number of elements four of their publishers and we are going to see both of these subscribers in action in a second so to help you better understand what you've just seen I'd like to illustrate things with a simple playground so here in this playground I've just imported Foundation and combined and I've also already added some code for a weather publisher to send some temperatures to ten twenty twenty four and so on degrees C and we want to get notified as soon as we have a notification that informs us about a temperature of more than 25 degrees C because then it's a summer day and this is something that we're interested in now to get started let's create our weather publisher and I'm going to use a pass through subject here this is also technically called a publisher because it publishes announcements of changes to the world and I have to specify two things a type and an arrow type and here I could just use era I could also use never which means I will never throw arrows this is also possible it would also be possible to give no type at all here so we could use void this is interesting for some scenarios in Swift UI for example but we are going to go with an integer here because our temperatures are just integers and for the era we could also use a custom type let's call this weather era and this is off type era and here one case could be things just happen so this is going to be our weather era that we are going to use for our publisher so this is a publisher now let's attach it to a subscriber and I'm just going to assign ours or whether publisher right here and now as I said we're just interested to get notified when we receive temperatures that are above 25 degrees so I can use an operator here just filter so very simple and I can just use each element that we receive and check if it is greater than 25 and if that is the case then I'd like to print a summer day off let's say 26 degrees Celsius so to do that I can use the sync operator which automatically also matches the output and failure types of the attached publisher so here we have the sync operator and in our closure we are going to get a value that we can now use so we can print for example a summer day of a specific degree Celsius value and now let's see what happens if we let our weather publisher and some pieces off data and as you can see we will only receive the values that are over twenty twenty five degrees Celsius so we get 26 28 and 30 and if I were to use my weather publisher again and send another completion about another value of let's say 18 and 18 degrees then we will not receive this message because our filter condition is not matched so this is how we can work with publishers subscribers and operators and I'd like to give you a quick example of what we can also do here I have just pasted another subscriber we're also attaching our weather publisher and we'd like to handle the different events so we receive a subscription the subscription can be used now in our closure so we'll get notified about a new subscription we will get notified about receiving an output receiving completion receiving a cancel and also print something when we receive a value so let's run this one more time maybe here on the bottom and as you can see once we actually subscribe to our publisher in another with another subscriber we get the message we have a new subscription to our pass through subject then you receive an output which is our output of 10 degrees 20 degrees and so on then we will also get the value of subscriber received a value of 10 degrees for example and we do not really see our completion and that failed for example with an error and this is because there was no error but we could send one so let's maybe just use our weather publisher here at the bottom one more time and this time we send a completion we use subscribers and completion and pass along the type of our era that we want to send this is going to be our weather era and this is going to be a failure and the reason is things just happen and if we now let this run again then you will see that we stopped the whole thing when we send actually the 30 degrees this is the last thing that we see and then our last output a subscription completed with a potential error and this is the error things just happen which is what we get from our receive completion right here and now after all this groundwork let's move one step further to using all of that in uikit and for that purpose I have created a very simple single view application not using Swift UI just using plain old UI care with a storyboard a view controller and so on and the purpose of this application is that we can turn on this switch which will also enable our send message button so when we allow messages then we can send a message and then we will also when we press this button we will see a new message here in this label so nothing fancy really but we will just use the combined framework for this to work and we're going to start in our view controller I have already created outlets for our switch for the sent button and for the message label and now what we need first is actually a publisher that we can use if we are allowed to actually send messages and for that we can use a property rapper called published and before we can use that we should import combined so now we have a combined framework available and also the published property wrapper if you'd like to know more about property wrappers go ahead and have a look at my latest video on swift UI there you will find a detailed explanation of what property wrappers are and what I'd like to do here is just create a property call can call can send messages which is just a bool and we're setting this to false and with this property wrapper published we can ask add a publisher to this property and what we will also need and let's maybe create that as a private property here let's call it switch subscriber and this is going to be of type Andy cancelable and there's going to be optional and this type any cancelable helps us with memory management since for example Eric's whiffed comes with a dispose bag and combines comes with this type Andy cancelable and this class calls cancel when our view controllers D initialized and make sure subscriptions are terminated early so with this ready we can start creating maybe a function let's call it setup processing chain and we're going to call this in viewdidload so let's say set a processing chain right here and now we can connect our subscriber with a publisher and we have this switch subscriber and we wanted we want to connect it with our can send messages publisher and to actually get access to the receive function of this publisher we have to use the dollar sign to actually get access to the property or the function from the property wrapper so we use can send meta messages and we want to receive elements from the publisher on the main thread so let's use dispatch Q and use the dispatch Q main and with that we can assign a specific key path on our button so we want to use the key path is enabled to actually enable our send button so we receive messages always receive elements from our can send messages publisher on the main thread and we assign it to the send button and it's is enabled property using this key path is enabled and with that our publisher and subscriber are connected to each other we also have to IB actions for the switch and for the sent message button and for to switch what we have to do now is change our can send messages boolean to the current state of our switch so here I'm just going to use the sender which we have as a parameter here in the did switch function and using the is on property and we think we always set the bool correctly so when our switches turn on we set this to true if it's off we set this to false and we will immediately notify our button to be actually enabled and as you can see currently the button is disabled so let's run this in the simulator and see if we can actually turn on our button by turning on the switch so you're in the simulator if I now activate my switch I also activate our send message button and we can actually now handle sending messages next so a very easy way to connect these two elements UI elements with each other using combine and now for our messages we again want to use a publisher and a subscriber maybe set this up also in setup processing chain and we're going to have a message publisher first so let's name this message publisher and in this case we're going to use a notification center publisher and if you have worked with a notification center before then you will feel that this is pretty familiar with things you've done earlier so we're going to use publisher here and we can initialize this with the default Center and a notification name so we can use default here and notification name let's say modification name and this is going to be new message so this is one way of defining a notification name another way would be to create an extension on the notification name therefore let's scroll up a little bit we will just do everything right here in one file so that it is not too confusing and I'm going to create tension here on modification the name and then we'll have a static constant called let's say new message and this is going to receive the notification name new message alright and with this extension what we can do is simply pass along a simple name which is new message and with that preventing any typos from our notification to be called or using it properly and now with our publisher ready we can actually create our message subscribers so let's create a message subscriber and we're using subscribers here use a sign to create a new subscriber for our object message label and the key path text so we're actually talking to the text property of our message label and now we can actually connect our our popper a publisher to our subscriber using the message publisher and subscribe using the message subscriber and there we have it let's quickly build that and let's find out that we get these two arrows telling us that the instant method subscribe requires The Times publisher output aka notification and string be equivalent and this is what I have told you earlier output and input types have to match earlier when we dealt with the Kent can send messages publisher we have used the assign operator and as you remember the assign and the sync operator both handle the usage of the same input and output types automatically but what can we do if we do not use this assign operator well we can use the map operator but we're going to do this in a second first of all since we are dealing with messages here I might want to create my own type for that so right on top of our view controller class and below the extension for our Norfolk name let me create a quick struct here let's call it message giving it to properties let's say we have the content which is string and we're going to have an author also a string so just that we have a type and that we know what we can work with and when do we actually want to send a message well when we press our button so let's maybe use our button function our IB action send messages or sent message first to create a message let's initialize that with a message not with the message label but with a message and the content the current time is just pass along a date object and the author is me so with that we have a message that we can send and then to actually send the message we use the Notification Center default and then we can just post our message using a notification name and an object and for the notification name we've already created that that would be new message and the object that we'd like to pass along is the message that we have just created before so now let's the deal with connecting our message publisher to the message subscriber properly using an operator to make the input and output types match so I'm going to use the map operator right here and as you can see currently we're receiving a notification because we're using the notification center publisher and what we can do now is taking this notification here as a parameter and returning an optional string just as we're required to do and then we can just return our notification in this notification we have an object this is the object that we're passing along here when we're posting the notification in send button and then we can just cast this object to a message object and in this message object we have the content and this is a string and if this does not work then we will simply return an empty string and if we build this one more time I'll era disappeared the types are matching and we have used successfully used our map operator for returning the proper type so we're having our message publisher we have connected it to our message subscriber and now we can run this into simulator and see if we can indeed send some messages I cannot send messages yet because my button is turned off so let's turn it on and send a message and there we have it as you can see every time I press the button I'm sending a new message indicated by this second counter here and this works really fine so this was a very quick example of how you can use the combined framework together with UI kid you've seen the theory you've seen it in practice I hope you enjoyed this if so give this video a thumbs up make sure to subscribe to not miss any future tutorials and I'll see you in the next one bye [Music] you
Info
Channel: Brian Advent
Views: 50,096
Rating: undefined out of 5
Keywords: Swift, Xcode (Software), OS X (Operating System), Core Data (Software), IOS (Software), Tutorial, programming, iphone, ipad, Macintosh (Computer), Apple Inc. (Organization), IOS 8, ios9, CloudKit, iOS10, Swift 3, firebase, firestore, ios11, swift 4, ios12, swift 5, ios13, combine, wwdc19
Id: RysM_XPNMTw
Channel Id: undefined
Length: 23min 29sec (1409 seconds)
Published: Fri Jul 05 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.