Getting Started with Combine (Practical Combine Framework Examples in UIKit & SwiftUI)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

thank you!

👍︎︎ 2 👤︎︎ u/GreedyAmbassador 📅︎︎ Apr 25 2021 🗫︎ replies
Captions
hey and welcome back to another video so in today's video we're actually going to be looking at how we can actually use the combined framework in ui kit and swift ui and how we can apply this to some practical examples so the first thing i'm going to do is actually go on to my github page with my youtube resources which i'll put a link for in the description box below and essentially what you want to do is you want to basically download this and then we basically want to use the folder here called getting started with combine you should see this folder here called getting started with combined all right cool so all you need to do is just open up the workspace and then you should see a list of all the um xcode projects that we're going to be going through so the first one that we're going to start on is introduction to functional programming so if you already know functional programming you can actually skip this chapter and actually go to the next chapter which is actually breaking down reactive programming what we're going to do is we're actually going to start off with functional programming and the reason why is because it's really important because essentially combining actually built on top of these functional programming and patterns now if you're someone who has no idea what functional programming is essentially what it is it's a way for you to basically almost like group your functions together and almost like combine them together so you basically um can perform multiple actions in a chain now what we're actually going to do is we're actually going to look at some functional um you know programming methods that come with swift and we're not gonna go through all of them because trust me there's a lot of them but essentially we go go through some and we're gonna see how we can basically refactor the code that we have on the screen here if you basically just open up the um if you open up there at the workspace if you just go to the first um xcode project here called intro to functional programming and then if you basically open up the playground and like i said before previously if you already know about functional programming you can actually skip ahead to the next one where we actually break down reactive programming but essentially what we have here is we basically have an array of items with some names in there even put a nigerian name in there represented so we've also got a function in there called filter nils so essentially what this function is going to do is it's going to basically remove um any nils from this array and give us back an array with no no values so if i run this um function now we'll see that we basically get all the names back without any no values which is cool but there's actually a way to basically do this um using functional programming and we don't have to write out all this logic ourselves we can actually just let these functions then change them and do it for us so one way to actually do this is by using a function in functional programming called compact map so what i'm going to do is i'm just going to type out this function and then we'll break down the syntax of it so what we basically have here is we have our um array of items but we now have this function called compact mac and essentially what compact map does is it basically iterates through an array of objects and it essentially removes any nils so if there's any nil values this function will actually remove it for us automatically so if we just look at this and then compare it to what we wrote here it's a lot cleaner because we don't actually have to write out all this boilerplate stuff we can just basically use this function and then we can actually chain on top of this function to change the original value which is what we're going to do next but before we do that we basically got these um curly braces here now essentially what this is doing is like a closure syntax so we're basically saying that we want to basically run this without the parentheses so we're using a closer syntax and if you use the closure syntax on one line like what we've done here we basically get this thing called um dollar sign zero and essentially what this means is it's basically the original value that you're iterating through so what this is is this is each object in the array that's actually going through so it's basically go through each object in the array and one when it finds a nil it won't return it back to you in the array what we're going to do is we're going to run this now and see what happens and as you can see we get the exact same result just by using this high order function now what i want to do is i actually want to basically take this out of the array and actually format with a list with separate commas now as you can see if we want to do that with this we'd have to add in more code which is what we don't want to do we want we don't want this to get too big so what we're going to do now is we're actually going to see how we can actually chain function all right cool so now we've done that what we basically done here is we basically are using more functions to chain and basically change the original value so we know about compound map but now we have something called map so what's the difference between these two so essentially what map does is it basically creates an array of objects and so this doesn't actually care for um nils so if you wanted to basically map your data to a specific type you can use map so what we're basically doing here is we're basically using map to basically create an array um of strings so this basically takes out any nodes but at this point it's still actually an optional array so we map it and basically almost like flatten it to an array of strings so what this drawing will do it will actually combine the entire array of strings that are not optional and basically put a separator between each one as you can see here so now what we're going to do is just go print this out and then let's just run it all right cool so as you can see we've now basically got our names flattened into one string and they're all separated by these um commas right cool so that's just like a brief introduction into functional programming and if you want to do a more detailed video then let me know in the comment section below but i'm also going to list some resources that i think are really handy for you to understand more about functional programming and we're still going to go through more functions as well because we're using combined so let's jump to the next section where we actually talk about what is um reactive programming so when working with combine it basically brings forward a new concept that you may not be used to called reactive programming reactive programming is essentially a pattern where we basically have a object that listens to some sort of event and when it receives a change or some sort of value it basically reacts to it so we basically make our ui react to changes now when working with combined there's two main concepts that um pretty much sum up all of reactive programming and these are and these are publishers and subscriptions so publishers of what you used to basically almost like i said before to publish emit an event and subscription is when you basically listen to um a change or an event being sent so let's actually break this down with a really simple example so if we look at our simple example what we basically have here is we basically have a switch so in our case the switch is basically our publisher so this is what we use to basically turn things on or off so think about switching your house now when you turn the switch on or off it's basically sending that event which is on or off and then what happens like i said is it sends the event and then once you the event is sent we basically can have a light bulb so the light bulb would essentially be our subscription so it basically listens to the event that we've sent which is you know was totally on our switch and it basically changes based on this event obviously if you switch on if you switch the light on then the light bulb will turn on and if you switch the light ball off the light bulb will turn off so it changes based on what is emitted what we're actually going to do now is actually go to the next chapter where we actually look at how we can actually use subscriptions and actually listen to changes and react to this now first example of you know where can we combine we'll go look at how we can use subscriptions and how counsible works so this project here we're actually going to basically build like a really simple timeline now in order to basically get onto this um in your workspace you want to make sure that you're editing the files and subscriptions and consoles and you want to make sure that the target you select matches as well so subscription and cancels now i've just read this on my machine now and as you can see you don't need to build any dui i've already done it for you because we just want to focus on um combine you know i got you like that so what we're going to do is we're going to see how we can actually use combine to basically create like a really simple timer so let's do that now so with combine the first we need to do is obviously import it so let's do that now and then if you just go all the way down or just above the load view we actually need to basically create a cancel to basically hold our subscription so i'm going to type this out and then break it down all right cool so why do we need to do this so essentially we combine what actually happens is when you're basically creating subscriptions where you want to listen to changes you need to store that somewhere now if you don't store the subscription somewhere what will actually happen is essentially it's just not going to work so what we do here is we basically create a global variable to hold our subscription so when our view controllers are live our subscription doesn't actually get destroyed until we actually destroy it or it needs to be destroyed so the next one we need to do is actually write out the code to basically handle our time on logic so i'm going to type this up cool so that was a lot of typing so let's break that down so what we actually do is we basically store our timer in our subscription so we like i said before we can keep it alive but let's actually just walk through each function that we basically used and chained on top of each other so what we basically here is we basically use the timer and that comes with you know swift and we basically use this function called publish now this basically creates a publisher for the actual timer object itself and we essentially say that every single one second i should keep on going on the main thread and within and the common along for the loop thread so this is basically going to run this timer every single second on the main thread and then what we're going to basically do here they almost like connects the um timer to um our publisher so we can actually listen to the changes for the timer and we basically got this function here called scan so essentially what this scan is doing is it basically allows you to basically create a value and almost like change it so in our case what we're doing is we're basically a scan from zero and what this is gonna do is actually go to increment it by one so this essentially is where we increment in our seconds by one so hence why it's called count and then we use this function here called sync so sync is when you want to basically get the final value out of the um subscription so there's two um completion handlers here so there's completion um so this completion is when the subscription has completely been killed and it's finished and receive value is when the value within the subscription changes so in our case when the count changes and we're actually going to access it within this receive value here and then we basically just print out a message to show what we've got format the label with and we just basically assign this label with uh how we format the seconds and in terms of this format it's not something i wrote so i actually put a reference where i just basically got this from stack overflow so essentially we just use this function to format these seconds into hours minutes and seconds all right cool so what we're going to do now is we're going to rerun this so if we just i just stopped this if i just basically just run this subscription accountables on my device here and if i just hit the start button you'll see now that our timer is updating and the labels being changed as well all right cool but how do we get the stop button to actually stop the timer essentially what we need to do is we basically need to essentially stop this subscription from running all the time so in order to do that it's fairly straightforward all we need to do in here is there's actually two ways of doing it i'll show you the way that i prefer so one way of doing it is we could basically use this we could basically set the subscription to nil now the reason why we can subset this subscription to nils because we defined it as an optional here but i don't really like doing this to be honest with you and so subscription any cancer balls actually comes with a function called cancel so we just say dot cancel this essentially will basically stop our subscription and this will actually stop please essentially just put that in stop timer and then just stop it and then run it again so now we hit start this is going to run every single second and now if we hit stop you'll see that it actually stops um our subscription and if we hit start again it restarts the next one we're going to do is let's go look at how we can actually combine subscriptions together and actually see how we can combine two publishers and subscribe to their changes so let's look into that now so in this part we're basically a look at how we can combine two publishers and basically change the value when we subscribe to it so what you need to do here is you need to basically go to the xcode project called combining subscriptions essentially what we have here is we basically have two publishers so we have one publisher which is a optional array of strings as you can see here with all the foods and we've got another publisher here which is an optional array strings as well with a bunch of names as well so it's worth noting here the syntax so essentially what we're basically saying here is that this is almost like a um collection of objects that we're basically going to publish and listen to and the type of this is this type here so it's an array with optional strings in it now this keyword never basically means that there's no errors so this can never fail so hence why it's called neville and at the end to turn this into a publisher this array we basically use the dot publisher um annotation now obviously this is only available with combined so if this is something you want to do in your own personal project then you want to make sure that you import combine so the first thing i'm going to do is i'm actually going to basically just write out a bit of code and just show you how we can actually subscribe to these publishers and basically manipulate the values that we get back from it so i'm just gonna do this now all right cool so essentially what we've done here is we basically got our people publisher and we basically combined it with our meals so what's going to happen is that these two publishers are actually going to essentially you know listen to each other and then what we're going to do is we're basically going to grab the values from both of these published arrays so in the completion we basically just print out the completion subscription but in received value you'll see something interesting so essentially now we actually have access to person and meal now the order of this year is basically based on the order of the um way that you combine the two published arrays so because we define people here first that's the first one and then we've been basically combining meals to it which is the second one you can see meal here so now what we're going to do is we're basically going to listen to what these two published arrays emit so essentially when it goes through each values it goes through this value this value this value and so on and so forth and we're basically going to just literally create our own custom string which tells us what meal a person likes to eat so let's just run this now and see what happens in the playground okay cool and as you can see here we basically get all the people so my name and all the foods that they like to eat but there's two things here that's pretty interesting so the first thing is that this actually printed out subscription finish now why did it do that well the reason why it's printed out subscription finished here is because it's actually finished going through every single value within the publish sequence so when it finishes going through everything it will tell you hey i'm done so at that point the subscription doesn't need to be alive anymore it's basically you can basically if it's still alive you can basically get rid of it or if it hasn't been disposed of you can dispose of it but the second thing is we actually do have a nil here now obviously this isn't the best because if you had this on a ui you wouldn't want to show something empty we can actually do we can actually use a functional um programming function called filter to basically take out and not print out any values that have a nil so i'm just going to type this out and then break it down what we basically said here is we basically want to filter out any um people and any meals that i know so this will actually basically return the array of people and meals where there's basically um a value inside of it so we won't get any nails so let's actually run this now and as you can see jack here doesn't appear because meals is actually nil so it doesn't print out the value no now this is a valid way of doing it but we probably could do this a better way so a better way of actually handling all this to be honest with you would be to have a function that throws an error and basically tells us when something's gone wrong so if something has gone wrong we can handle it ourselves um that be either logging it or you know showing some sort of placeholder image or whatever it is what i'm going to do is i'm going to basically type out a bit of code in terms of how we can handle the errors and i basically have a function to basically validate that neither one of these are not nil so let me just do that now all right cool so let's just break this down a bit so what we basically have here is we basically have an enum called person error and essentially this is just our error for just handling you know any areas that we want to you know check for one of the areas that you want to check for is empty data so if there's any empty so there's any nils then we'll basically throw this and we basically just wrote an extension on our person error with a property called error description with a property called error description and what that's going to do is if the case is empty data then it's basically returned this message here we basically got this function here called validate now what this function does is it basically validates the person and the meal that gets passed into it and if everything's all good then it basically returns a string message so this is where we basically manipulate this is where we're going to basically manipulate our to publish arrays and just return a message or else if something goes wrong then we're basically throw an arrow and that error being that there's some empty data so now that we've got all this set up what we can actually do is rather than using filter we can basically use a function called try map and what trimap's gonna do is basically going to try and map the values so try and change um the values that we basically want to change to which in our case is a string and if it fails then what's going to do is that's going to throw an error and tell us what went wrong or if it was all good then it would just carry on like you would with any other function like map so what i'm going to do is i'm going to replace filter all right cool so now what we basically got here is we basically got our function here try map which is going to try and validate the person and the meal and now in our receive value we're not actually checking for two values we're actually checking for the message now this message is what this function has mapped it to so for us it's mapped it to a string because this is what we return here so we just basically print out that message now what we need to do in the completion to actually handle the error where if something actually does go wrong so what i'm going to do is i'm basically going to just delete this line and then because this completion is actually a result we can actually use a switch statement on this so let's do that now cool so what we're actually basically doing here is we're basically matching to the possible result that we can get from our completion so when the subscription has finished it'll basically print out finished and but if something goes wrong and it fails it'll actually print out that it failed and why it failed and so we can actually try to cast it as our custom enum and person error but if it fails and it can't because the person error then we'll just basically default the you know default arrow and the localized description so what i'm going to do now is i'm basically going to run this and see what happens let's do that now all right cool as you can see it basically does print out that you know i enjoy burgers bob enjoys and toyo enjoys but when it fails it basically tells us that something failed so it basically says that there was a nil value somewhere so at this point here if something went wrong we can actually handle any errors that we wanted to but what i'm going to do is i'm going to basically fix this and i'm actually going to change this to some other food so let's just do that now and you can do you can do whatever meal you like and i'm just gonna go to the emojis i'm just gonna choose to add some bacon in so what i'm gonna do here is i'm just gonna basically run this again and as you can see now it actually prints out everyone and it actually tells us that it's finished publishing or the emitting all the events and nothing has failed so you can see here if we just quickly just review from top to bottom again that we can easily combine two publishers so two publishers are doing two different actions we can actually validate and actually change the value based on the result that we get back from these two publishers and we can actually basically observe the value in receive value or handle whenever it's finished or failed so what we want to do is we actually want to see how we can actually assign subscriptions to values so other values automatically update and we're actually going to see how we can apply this in ui kit by assigning a value to a ui component okay cool so for the next section we're actually looking at how we can actually assign subscriptions to of a value so let's say you have a publisher where you basically admit about your regards yeah we can actually assign the new value to an existing value within a class for example now for this uh you want to make sure that you're looking at the project called assigning subscriptions and you want to make sure that the target is also selected as well so what we basically have here is we basically have a class called levels manager which basically has the user's level and whenever this value changes we're actually going to print out the user's level to the console so what i essentially want to do is i basically want to change this value so i want to basically publish a event to change this value and whenever this value changes i want to basically print it out into the console like i said before but what we're going to do is we're going to basically use a range so we can actually loop through this so look for a range of values and actually update this all right cool so what we're basically doing here is essentially basically create a initialization of our class levels manager and we basically got this range so this is basically obviously finding a collection of numbers from zero to 100 and we basically got our subscription here within our cancer ball and and then we basically get our range and we basically turn this range into a publisher so what this is going to do now because it's a publisher is basically go through every single value between 0 to 100 and we basically have this syntax here which you may not have saw before so what this is basically called is it's literally called key puffs so we're basically saying in the assign function on it within the levels manager the value that gets emitted from this range so zero one two three up to a hundred we want to assign the value that gets emitted to level within our levels manager so this is you basically saying that you want to check you want to basically store any values that are emitted to this level inside of here so what we're going to do is just run this and see what happens cool as you can see we just look at the console you basically see that all the levels from zero to 100 are being printed out in the console which is pretty sick but this is just an example of me just basically showing you how you can actually like bind you know other values to a publisher so whenever it subscribes to the publisher it changes and but it's also worth noting that before we carry on into the next part that this assigned to isn't actually the always the best way of actually you know binding values to other you know objects and because it can cause memory leaks so in this case it's fine but in the next well not the next chapter but in future chapters we'll actually talk about how we can basically avoid retain cycles with assigned to now the next thing i want to do is i basically want you to go to the view controller file i basically just want you to just run this so we can see the app so as you can see in this example in our view controller we basically have a view here with a text field and a label so what we're actually going to do is we're actually going to basically see how we can actually bind a text field to an actual label so when we type in here this will automatically get updated so the first thing that we're going to do in our view controller is as usual is import combine now this time we're actually going to basically create a set of constables to hold our subscriptions and i'll explain later on why we need to do that but the reason why we need to actually create this set of subscriptions is because we want to bind this text field to our subscriptions so like i said before you'll basically keep the subscription alive as long as the view controller is alive but if we want to bind to multiple text fields we can actually you know just assign them to the set so they all live within this collection of any constables so once this is disposed of all those subscriptions will be killed within this set the next thing we want to do is we actually want to basically create a subscription for our text field and then assign that to our label so it automatically listens to updates so below the self function we're just going to basically create a function called setup subscriptions and then what i want to do is i basically wanted to just call this function below the setup function here and then within this function sub subscriptions what we're going to do is we're actually going to type out some code to actually do what i said previously so we'll type out and then break it down all right cool so what we're basically saying here is we're basically using the notification center and if you've never worked with this before essentially this is just like a framework in ios development that allows you to basically send um updates you can basically push a event or a notification and actually listen to when it's been sent and then we basically just get a default notification center within the system and we basically get a publisher for it so what this essentially is saying here is we basically want to listen to the text the change notification on our text field so our text field is called input text field so whenever there's a change within the text for our text field this is basically going to fire essentially so what we're then going to do is we're basically going to get the text value out of our text field so that's why we basically have to cast it as a ui text field and then access the property text and this will basically because it's um compact marked it will basically remove any um nils from that and then what we're going to do is we go basically flatten the value from the text of our text field into a string here i just got entered wrong it's not an entered yeah entered oh god you spot entered so what we're going to do is we're going to flatten that string here and then this bit here is really interesting so what we're basically saying here is that when we flatten the string we're basically going to assign the value to our text label so this label here on the text property of the label so notice how on the key path and when you assign it on the object you can access any property that you want so in our case here we're accessing the text property on our label and assigning this value into here and then we simply store our subscriptions store our publisher into the subscriptions here now what this symbol is here is it essentially it basically means that this property here is a in and out property so in and out basically means that you can pass a value into the function and when you pass the value into a function you can actually change the value as well so this bit here is essentially what will basically help us manage our subscriptions and dispose of it when it needs to be disposed of so it basically changes the collection of subscriptions when it needs to what we're going to do now is we're basically going to stop this and we're just going to basically run this piece of code here and now if i go into a text field and just type in something like hello you can now see that the value that i'm actually typing in is updating automatically within the label which is pretty cool so just by writing these few lines of code here with you know chaining these functions you can basically bind a text field to a label fairly easily all right cool so now the next thing that i want to do is i basically want to look at essentially some type of publishers now the first publisher we're going to look at is something called a current value subject so with current value subjects essentially what it allows you to do is it basically allows you to hold um you know a value within a publisher and essentially allows you to observe that value so you can get the current value and as well you can basically change the value as well so this is really useful when you want to basically like emit a new value and observe changes over time so a good example of where this would be useful would be like in a form for example because obviously when people are typing in a form you know they can always change any text field at any moment but what we're actually going to do here is we're actually going to basically simulate that so we basically got a basic form here where someone could type in their first name last name and occupation what we're going to do is we're going to basically collect the values that someone types it in and we're going to do some very basic form validation so if the form is valid then print it out into the console and if it isn't valid the most awesome kind of error message to let them know that hey you know you don't got messed up so let's do that now so as usual the first thing we need to do in our project is import combined okay cool and then what we'll basically do here is just below all our ui we're basically going to create our current subject value and i'm actually going to break down the syntax for you so just bear me a second all right cool so now let's break this down so as you can see we've got our current value subject here and we basically can declare the value that we basically want to you know observe and change and we basically can also define whether there's an error or not so in this case we have defined that as an error rather than using the never type so we basically have to give our current subject value a default type so d sorry they basically have to give our current value subject a default value because this is what we're going to change and observe over time in our case we're basically just giving it a person object and with a first name and last name now this is something that doesn't come with swift it's something that i provided for you so we just check out this model essentially this is just a person with these properties and as you can see i basically created a extension as well so we can basically print out a message and also check to see if this person is valid so they filled out all the correct details all right cool so the next thing that we're going to do is basically create our subscription so let's do that now all right cool and now what we need to do is we actually need to bind each one of these text fields to each one of these properties within our struct so what we're going to do below the setup is we're basically going to what we're going to do now is we're basically going to create a function to basically handle that specific case and we're basically creating a new function called set up input subscriptions to listen to all three text fields so let's just do that now all right cool so now before we actually carry on and do the rest of the text fields i just wanted to kind of just break this down so we can actually you know just discuss it though it's similar to the last section where we basically bound our text field to a label but there is a small difference so up until the compound map and where we basically convert and get the text value from our text field rather than using a sign now we use sync now the reason why we're using sync is you might spot that i'm using weak self here now the reason why i'm using wiki self here is because i don't want that to be a retain cycle with i'm using assigned to so using weak self will basically make sure that this gets disposed of and we don't have any strong references within this view controller now on the next line you can see here that we're actually assigning it to the person so our person above here we're basically accessing the value which is basically our default value here and changing the first name so we're basically assigning the value from the text field to our first name now what's gonna happen here essentially is that this is actually going to automatically update our value here and if we wanted to as well we can actually subscribe to the changes on person and actually listen and output that as well all right cool so now what i'm going to do is we're going to basically type out the rest of this for each text field so i'm just going to do that now all right cool and as you can see we're now signing up for each text field so in the last name text field here we're going to change the last name and occupation we're going to change the occupation and we need to actually use this function within our load view let's do that now what we need to do is because we're actually changing this person every single time these text fields are changing we need to basically create a you know a subscription to basically listen to the changes that we're making to the person so below yourself input subscriptions let's create a new function i'm just going to call it a cell person subscription what we're going to do in this description here essentially is we're just going to basically listen to the changes that get made to that person so let's do that now cool so what we're basically doing here now they're basically listening to the changes that get made to this person so this here this sync is basically going to get the most recent value from our person and we're basically printing that out in the console and store this subscription alongside our other subscriptions in our set so now what we need to do is we need to actually call this person subscriptions after our input subscriptions let's just add it here all right cool and um it's worth knowing the reason why i'm using load view so the reason why you probably don't want to do this and like you will appear and whatnot is because we essentially just want this to get set up instantly and also if you set this open view will appear um essentially what's going to happen is every single time the view appears you're going to keep on creating these subscriptions which probably don't want to do now let's just stop this and i'm just going to run this quite cool so instantly as you can see here it's automatically emitting our default value to the console here with the value received so now let's just type in our first name and as you can see as we type our first name and it prints out and but essentially you can see here i was putting out the first name as i changed in the person and if i just do my last name you can see there and if i do my occupation cool so you can see now that we're able to actually emit changes and observe the changes to our current value subject so this is really useful when you want to basically you know like i said before observe changes and also send events to it as well now the next we want to do is when someone taps the confirm button i actually want to combine all of this together and basically print out a message in the console to say hey this is the information that you know someone has entered and if any of these are empty i want to handle any of those errors as well so in order to do that what we're going to do is in our button if you scroll up here we basically have a confirmed touch now one go do is go type out a bit of code and then break it down for you okay cool so what we're basically saying here that if our form is valid then what we're going to basically do is we're basically going to send a completion to basically tell our subscription that we're done or else we're just going to show an error message on the screen so what we're going to do down below here now is essentially we're just going to basically listen to the finished and when it's finished we'll basically just print out the value so in here what we're going to do is make a few changes all right cool so i'm basically saying here that when we basically get completion and it's finished and we're just going to say this was the final input i'm gonna go basically get the message now because this is optional we have to give it a you give it a um default value if it's ever nil which this could be an empty string so what i'm gonna do is i'm gonna run this now and now if we hit this you'll see that we get our form is invalid because it's not valid in our vr extension if i just fill out this information now you'll see that it's updating so now if i hit confirm because it's now valid this is our final input and now the subscription stream has finished and it's been closed all right cool so it's really important that you when you finish with a subscription you tell it that you're finished with it so you don't just have it just you know chilling in memory and so when it's when you're done with it just say you're done with it and the next publisher we're going to look at is pass through subjects and essentially this is similar to current value subject but it's a bit different so like i said before how we have current value subject we also have something called pass through subject now there are differences so with current value subject you can basically emit and observe the value as it changes over time past your subject is a bit different because essentially all it does is it just basically emits a value so you can't actually observe and change any changes it just basically just sends a new value so what we're going to basically do is we're basically going to build a view controller where if you basically enter um some bad words at least three times or basically give us some sort of like you know warning um and but basically see how we can actually use classroom subject alongside current value subject and see how the two are different and how you can basically combine them together within your code so as you can see here when i run the passthrough subjects project we just have a text field and a comment button here and in the folder pass through subjects in the prexcore project we actually need to create a view model for managing the comments that people make so what i'm going to do here is i'm just going to create a new folder here called view model and within this folder we're going to basically create our comments view model so i'm just going to type out some code and then break it down all right cool so now let's just break this down so we basically find the final class here and reason why we use finals because we don't want this class to be able to be subclassed and if we look at the syntax for property subject it's very similar to current value subject except if you notice we actually don't give it a default value and like i said previously before that's because you don't observe any changes to its current value just use this to emit events so the type that we're going to basically be emitting and publishing is type string and you can see here that i never fail so which is why we put neville and all we have here is a function called um send and then we basically use the send and function for the password subject to basically emit um that unpublished the comment that someone has entered in the text field all right so what we're going to do now is we're basically going to create a subscription and within this view model so we can basically see how classroom subject works and how we don't observe the changes we just listen to the events that are sent so i'm going to do a bit more typing all right cool so let's just break this down so we basically created our subscriptions and obviously it's been marked as private so it's only within this class we have our initializer for this view model so whenever we initialize this class we're going to set up our subscriptions within our subscriptions we're basically just going to observe and basically grab the value when it's published via sync and it's basically printing that out into the console so we can just see the new comment so what we want to do now is we want to basically use this view model within our view controller so we can actually start sending some comments and seeing it in the console so within the view controller let's just initialize that class here and the next we want to do is in our comment the touch whenever someone taps this button we just want to basically print out whatever's in the text field so let's use that send function now all right cool so you can see we're just basically just passing in the text views text property and i'll just print it out so now let's just stop and run this and if i just type in here hello you can now see that our subscription has been set up and it's basically outputting that out into when i make it bigger and it's actually outputted now into the console so i just say world you can see how it prints that out all right cool well what i want to do is i want to do some validation on this because if i just basically leave this empty now you can see that it can work so what we want to do is we basically want to do our validation for our empty state first and then we're going to see how to handle the bad words so let's just filter out whenever this is basically empty and it won't put it into the console all right cool so essentially what we're saying here is if it's not empty then it can carry on and it can actually get the volume and print out into the console but if this doesn't if this is empty then this will actually not print out into the console so let's just stop that and try that out now all right cool so i'm just going to type in here hello you can see it prints out hello and if i delete all the text i just enter you can see that nothing when i'm tapping the button it's actually been printed out to the um console all right sweet so now that we've handled the empty state what we need to do is we actually need to handle if someone types in some bad words so at the top of your comments view model and we're basically just going to create an array of bad words cool and now what we're going to do we're just basically just going to write out the implementation for checking whether it actually is a bad word or not so let's do that now so what we're basically doing here is we're basically checking to see if the array bad word contains a text that someone's typed in and if someone does enter a bad word what we want to do is we basically want to give the person free strike so if they basically enter in the bad word three times then what we're going to do is we're basically going to block their account so we're going to basically like simulate blocking someone's account so in order to do this we're going to need to basically create a new view model called account view model so let's do that now so in the view model folder if you just create that and then what i'm going to do is i'm just going to do a bit of typing and then we'll break down as usual all right cool so we basically have our class here account view model and essentially in this class we basically have two states an account could possibly be in so an account could basically be either active or banned so i don't think i need to break that down so we basically also have a warning limit so this is the three strikes i was talking about so it's the limit that you're basically allowed to basically post a bad word and then essentially what we have here is we basically have two current value subjects so what we're going to do is we're going to basically see how this is different from you know publish uh sorry we're going to see how this is different from pass through subjects and by seeing how we can actually observe the value as it changes rather than just emit an event and within this one we basically have a user's account status so this is so we can observe the change in the user's account status so right now by default it's active and this is the warnings current value subject where we basically observe the number of warnings we've given someone and by default you can see here that it's also zero as well so we're basically almost like starting them both off from a default state and we basically have our set of um constables where we'll basically store our subscriptions all right cool the next thing that we need to do is we actually need to basically write a function that actually increases the user's warning so whenever someone does something like fugazi then we'll actually basically increase the warning so let's do that now different to the pass through subject because we're actually able to access the value of this and increment it by one and what we're going to do here is we're going to basically print out the warning in here now the next thing that we're going to do is we're actually going to observe our warnings and essentially what we're going to do is when it reaches a certain amount we're going to basically change the user account status so let's do that now cool so let's break that down so what we've done is we basically created our subscription here and we basically use it whenever this class is initialized within our subscription we're basically checking out warnings and we're basically filtering out value so we're basically using weak self because like i said before we don't want to create a weak a strong reference and you know like a retaining cycle and what we're basically saying here is that if the value is greater than or equal to the warnings that we basically set so the warning limit which is free then we want to essentially continue to basically sync and get that value out if we if we need it so if this is actually less than three the value in um warnings then it actually will not hit and execute this but if it is greater than or equal to free what we're going to basically do is again use weak self again and we're basically going to change our users account status value to band so the users actually could be banned from using this app so what we're going to basically do now is we need to actually see how we can actually tie our account view model to our comments view model and in order to do that we're going to use some dependency injection so we're essentially going to need to inject our account view model into our comments view model so let's do that now cool so as you can see in our commons view model we basically defined our account view model and we're actually going to inject it via the initializer and then set it up so now what we need to do is where we basically put the comment to handle bad words if the bad word if someone's actually entered a bad word in what we want to do here is rather than having this comment we actually want to use our account view model to increase the warning so let's do that all right cool and then now what we finally need to do and then now what we finally need to do is essentially we need to actually handle um the account like state has been changed in our view controller so let's handle that now so the first thing that we need to do is where we declared our comments view model we're actually going to change and the syntax for this and actually use our account view model as well so the first thing we want to do is i'm just going to type this out and then break it down all right cool so you may have clocked that i changed the comments view model from being a constant to a lazy um virus or a lazy computer profit well not pause so i changed it from a lazy initialization now there is a reason for that so the reason why i've done that is so we can actually inject our account view model um globally at runtime and what's basically gonna happen now is because we define these two as lazy bars and they're only going to be initialized when we actually use them now these two do get used and well the comments view model gets used when you send um a comment but the account view model will get used when we actually you know load up you didn't set up the subscription to listen to the account state is changing so that's how we're able to inject it into our manager like this if you just do this it won't work because it's not lazily created so you'll get an error like that so make sure that you mark them as lazy so now what we want to do is we want to basically listen and subscribe to the changes for our account view model so just below the setup function i'm going to create a new function to basically listen to that subscription then we're going to use this function here underneath the setup and then within our function i'm going to do a bit of typing out and then as usual break it down cool so now the first thing to note is that we have to create our subscription at the top because we want to you know subscribe and listen to these changes so make sure you define a set of any constable below the view models and then if you just go down below in our function now what we're basically doing here is in our account view model we're basically going to get the user's account status that we defined so the constant and then we're basically going to um sync so we basically want to listen to the changes in this constant um and then basically get the status we're using weak self again so we don't have to you know we don't have any retaining cycles and if the status has changed and it's now banned then we're going to show an alert so this show block is a custom function that i wrote in an extension on the view controller so we're going to show the band and then we're just going to store that in our subscription so our set of subscriptions so it's very important as well to note that the user account status the reason why i create this as a constant is because i don't want someone to be able to change either this or this um from outside of this class and so i kind of want to protect them so that's why they're constants you can't really change them um like willy-nilly um so what we're going to do now is we're basically going to test this out and see how this works so i'm just gonna run this i'm just gonna put some comments in you can see here it's working fine so great video all right cool so now if i put in nothing and hit enter you can see that nothing gets printed now let's test out how it handles these bad words so if you just go back to our array the first bad word that we have is the um poop emoji so i'm just going to paste that in and then hit comment so now we've hit our first warning and now i'm going to copy the aubergine the eggplant emoji because someone's been getting a bit excited then paste that in and now we're on our second warning and now if i just completely if i comment this again you'll see now that we have third warning and now our account is blocked and you can see your message here you fought for you were tough right well guess what you're banned so don't be messing around so as you can see here you can see how powerful it is to basically combined and pass-through subjects with current value subjects where you can use the pass-through subjects to basically emit and values and events and use a current value subject to basically listen to those changes and basically update your ui so these two are actually we'll go look at is multi-threading so what is um let's say multi-project well so what is the multi-threading so essentially multi-threading is when you basically want to move processes onto different threads so imagine you basically have like a motorway so rather than having one lane on a motorway there's three different motorways and that allows each car to basically move through the motorway quicker so essentially in programming or in ios development in general and we can basically use multi-threading to basically offset heavy tasks onto a separate thread now why would you want to do that so let's say for example if you were downloading an image or you will call an api you don't want to block the ui so you don't want to block someone from using the app just so you can download an image or call an api service so by you moving the task onto a background thread you basically allow the user to keep on using your app as normal and then when that process is finished you can then basically update the ui based on the response so if you look at our example here we basically have a box where we're going to download an image and when we download the image we're essentially going to just show that um on the ui so we're not going to block the main thread we're just going to basically download the image on a background thread and then update it on the main thread so we're going to see what image we're going to get here so i'm going to surprise you so what we need to do now create our view model to basically handle downloading this image so if you go into the multi-threading target and project let's create a new folder let's create a new folder called viewmodels and then within this we're going to basically create our image image downloader viewmodel all right cool so as you can see here um because we're working with images we're basically going to import uikit and combine of course but what i've actually done here is i've actually basically used a pass through subject rather than a current value subject and the reason why he's a passionate subject because i basically just want this um constant here to basically emit and tell me when there's a new image so i don't want to observe it i just wanted to descend an image so so this is where you have to start thinking about which one it is you want to use because you know we just want this to essentially act as an event to basically give us a new image so we basically have an optional ui image and the there's not going to be an error so it's never and we've got our subscriptions to hold any subscriptions that we want to basically handle all right cool so what we're going to do now is we're going to basically type out the function to basically download the image so i'm going to type this out but it's quite long and then we'll basically break down what each that is doing all right cool so let's break this down so essentially we're going to use url session so if you never come across this before url session is essentially what you use to basically like download and from some sort of um service so we're basically to access the url session shared and url session now comes with this data task publisher which is what you can use with combine now by default it's interesting so by default url session is um on the background thread so you don't actually need to subscribe to on the background thread but the reason why we're subscribing to on the background thread here is because we want to just see um how it handles events so i just want to basically handle the um subscriptions myself so this handle event i think actually puts it back onto the main thread so that's why i'm forcing it onto the background thread here so in handle event so when this starts and it receives a subscription so when we subscribe to this what's gonna happen is basically going to print out for me whether this is on the main thread or not and when we basically receive a new value and it's going to tell me if it's on the main point or not and when it finally just finishes and the whole subscription has completed it's going to do the exact same thing so the next thing we need to do now is essentially is we need to actually um use this function within our view model to see how it handles it when we try to download an image and see what thread it puts it on so let's do that now so in our view controller let's just use our view model cool and then when someone taps the button we're going to pass in this image link to basically see how it handles the threads so let's do that now all right cool so what i'm going to do now is just run this and then tap that button to see what happens so as you can see it starts a subscription on the main it starts on the main thread which is false so it's not on the main thread and when it receives and it finishes it's not on the main thread either so the entire work has been done on the background thread so we're not actually blocking our ui here we're actually doing work in the background all right cool so what you want to do now is when someone taps on this button i actually want to set this image to a placeholder in the meantime so the user sees some sort of placeholder image and then when the service comes back with a result we want to update this with the actual image from the service now if we just go back into our image downloader view model what we want to do here is in our handle events just below the stand subscriptions i actually want to set the placeholder image on the main thread now when you're working with ui nine times out of ten um you wanna do all your ui work on the main thread so let me type this on and break it down for you all right cool so what we're basically saying here is we're basically accessing the system's main thread here ourselves manually and then we're basically going to force or not fall but we basically want to send and ui image so we can basically you know get that image and set it to our um image view which is what we'll do in a second but we're basically setting it to uh placeholder so this ui image is actually something that i've added into the project for you so if you go into the assets folder you'll see this placeholder image here so this is something i've added and what it's going to do is this is actually going to call this function on the main thread so just so we can see that i'm going to put a message here basically say setting so now we can see whether the placeholder is being set on the main thread so now the next thing we want to do is we want to actually assign our image to our image view in our view controller so let's do that now so in our view controller below our setup function let's create a new function called setup image subscription and then what we want to do is we want to call this function after our load view cool so inside of here what we need to do is essentially we need to actually create um a subscription and to hold this inside of so let's do that at the top here all right cool and then we need to assign this and we need to store our image view subscription in here so let's just type this out and then break it down all right cool so similar to the previous chapter before we bound our text field to our label what we're doing here is we're actually binding the image that gets published from our passthrough subject to our image views image property so you can see here how we're accessing the image property using the keepass syntax and then we store um that subscription and within our subscription set what we're going to do now is we're going to run the app and actually see if this actually sets our placeholder so let's do that now so now you tap the button you can see that actually does set it to the placeholder and just look at our messages here we do get to see that the placeholder is actually being set on the main thread which is exactly what we want all right cool so now the next step that we need to actually do is we actually need to download this image from our url and actually push it back to our image view and put that on the main thread as well so in order to do that we're going to use a high order function called receive on which comes with combined so what i like to do is it allows you to receive events on a certain thread so i'm going to type this out and then break it down right cool so let's break this down so after we handle our events for our placeholder what we're basically doing now is we're actually getting the data that we got back from our service call we're basically going to turn it into a ui image so this could be an optional ui image and then what we're going to do is we're going to receive any um events after this on the main thread so this sync is actually going to be handled on the main thread so if when it completes let's go print out this message but when we receive this value we're going to basically push it so we go basically emit it using our pass through subject so our image view gets updated and we're going to basically also tell our current image and subscription that you know you're finished you've completed so we don't actually need um this subscription anymore so we're basically just gonna say you're dumb so now let's run this and see what happens and let's see what picture that we get so we just run this again now and then let's just tap this button download cool and as you can see we get my mind and craig in it so essentially um we look at the logs let's just look at the logs and let's just basically like explore us a bit so you can see here that when we receive our image is on the main thread which is what we want and also as well when it finishes the subscription it's also finished on the main thread as well so we get exactly what we want here we run our task on the background so we don't block the ui and then we basically receive our image once everything's completed all the process is completed back onto the main thread to update our ui so it's like a seamless smooth experience and we also get iman craig looking at the m1 macbooks so it's a win-win for everyone but it's really important that you you know focus on these topics because it's pretty important to ios development now the next topic we go look at is memory management so we're actually going to see how important it is and how to basically make sure that we don't create retain cycles using combine all right cool so now what we're going to do is we're going to see how to handle memory management in combined so if you just open up memory management and the project here and the playground you should see a class here so account view model and this account view model essentially has a account state and so a enum for the account state are struct here for the account with the username and their status we have a current value subject here so we can observe the changes to a user and also you know publish new changes as well and we basically also have a enum here so account state which actually tells us the user's current um account state as well so what we're basically saying here and is whenever we change the users whenever we basically change the user status property here we want to also assign that new status from here into our private variable as well so we're saying that we want to store the state on self self being this view model and it's going to be stored in their subscriptions and when we don't need this class anymore and it gets de-initialized we're going to print out this message here so let's see how we can actually create our view model and actually see how to de-initialize it so i'm going to type out all right cool so what we basically got here is we basically got a variable for our view model it's an optional account view model the reason why it's optional is so i can dispose of it myself and basically the initial the initialize the class what we're going to do here we're going to basically change the user's status to inactive and then that should update this account state because we've actually assigned and bound our account state to any changes that happens on the user status so what i'm going to do is run this now and see what happens as you can see now it basically when we change it to inactive it basically prints out that the user status has changed to inactive all right cool so the next thing i want to do is i want to actually de-initialize this object so i want to dispose of it because i don't need it anymore so let's do that now so if i set this to nil realistically this d initialize we want it to execute so let's do that now so as you can see we've executed all this code but our view model does not get the initialize now the reason why that is because we basically find self here so because we defined that we want to basically assign our value from our status of any changes to our status to our account state on self which is this view model what we've essentially done here now is we basically create a retain cycle because when you define self here like this you basically create a stronger reference between your subscription and your view model so there's no way to dispose of it so in order to basically fix this rather than using assigned to on self we're going to basically use sync like we've been using previously before so let's change this from assign to to sync and what we're going to do here is we're basically going to use weak self all we're going to do here is we're going to basically just make sure that we just basically set our account state to our value right call so now by us using sync rather than assigned to we've actually removed our memory and leak so our return cycle so when you're working with view models and you want to assign a value to another value like this nine times out of ten just i would just go with sync rather than assign two so you don't get any retain cycles so now let's run all this and see what happens and as you can see now because we're not we're not creating a strong reference type within our view model we're able to easily de-initialize it and release our view model when we set it to nil so like i said before just try to stick to sync unless you know 100 percent that sign two will not create a retained cycle right so the next example we'll go look at is how we can actually work with combine in swift ui so with swift ui you basically get some publishers without combine and some subscriptions so you basically get values that you can change and also listen to their values changing so what you what i want to do is basically go to the project and handling publishers in swift ui and in the views folder open up the contacts view and then essentially what i want to do is just basically change the target to be the same name so if we just run the simulator and swift ui here if i actually tap the plus button here you'll see that essentially a um screen pops up from the bottom and if we tap cancel it dismisses now what is actually handling present in that screen so in our contacts view we basically have a private variable called is presented but we've actually annotated with the type called at state so state is actually part of swift ui and essentially what that allows you to do is it basically allows you to observe the state and also make changes to it so what we're basically doing if we just scroll down below is when someone taps the add button we're basically changing is presented to true and we're observing it in our sheep as to whether it should be presented or not so this uh property here in the so this parameter here and is presented for our sheet is basically checking to see if this is true and if it is true then it's basically going to present our content so our view from the bottom you can see how swift ui already has some principles that are similar to combining terms of listening to values and changing them because this is no different to basically a current um subject value right so what we actually want to do on our contact screen is we essentially want to basically allow someone to enter in some information and when they hit add we want to basically update our list of contacts accordingly what we're going to do is in combine we're basically going to use something called an observable object and we're going to use a published and property wrapper now the published property is part of swift ui but we'll break that down after i finish typing this out so in here let's create a new folder called view model and then let's create a new with file called contacts view model and then what we're going to do is just import combine and i'll type this out and break it down all right cool so let's just break this down so what we basically have is we have a class here called contactv model which i'm not final and then we basically got this new um class that you may not saw before and so this is called an observable object so essentially what we're basically doing here with this class which comes with them combined is we're essentially going to say that we want to observe the changes that happen to this view model and within this view model as well we're basically use the app published and property wrapper here which basically allows us to basically publish events publish basically allows us to basically you know publish um changes within our observable object and also subscribe and listen to them as well so again this is no different to using a current value subject so we mark this as private set because i only want to allow someone to change this array of contacts within this class so i don't want to basically allow someone to change it from outside so you can only access it and observe it from outside but within this class you could basically listen to it and change it as well so what i'm going to do is i'm basically use this view model within our uh contacts view and basically see how we can actually use publish to basically switch between two different views so let's go to our contents view and then i'm just going to basically type this out and break it down all right cool so what we basically specified here is an observed object so because we marked our class as an observable object we're basically saying here that we want to observe and the changes to our viewmodel now you could use state object here if you wanted to but the reason why i'm using observed object is because i want to basically observe this view model within multiple views and so that's why i'm using in this case rather than using state object so we're going to do now is we're going to use the v models published property for the array to basically switch between showing that there's no contact on the screen and our list of contacts so i'm just going to type this out now all right cool so now let's just break this down so what we're basically saying here is that if the viewmodel contacts is empty so if i published we're basically checking our published array of contacts if that array is empty we're basically to show this content here so the no contacts and if it isn't empty so we actually have some values in the array we're basically going to create a lazy grid of items to show our list of contacts view so what we actually need to do now is we need to basically actually handle adding in our contacts via um this add new contact screen now so what we need to do is in our add contacts view we need to actually inject our observed object into our as content view so let's do that now okay cool and once we do that we should get some errors so the first error we should get is down here so all we need to do is just fix this by just basically injecting our viewmodel and then we shall get another arrow but the root of our contacts view and now all we need to do here is we need to actually pass through our viewmodel here let's do that now now that we're passing our contacts view model into our add contact view essentially what's going to happen is that the state of our view model so the published array is going to be maintained between different views so essentially what we're doing here is we're essentially passing data between views so if you make a change within the add contacts view it will automatically update within the main contacts view as well so what we want to do now is actually do that change so inside of add contacts view what we want to do in order to update our array is we basically want to bind our contact that someone's filled in and actually add it to the array but what we're gonna do is we're going to actually bind our new contact to our text fields so as you can see here we've got our new contact here which is a state variable so this is the new contact when someone wants to fill it in and we're basically binding each property within the contact um struct to our text fields so it basically automatically updates it so within our context view model we need to basically create a new function actually adds our contact into this array so let's do that now okay cool so this function simply just adds a new contact into this so once this changes it will actually update our view previously before which is our contacts view so now in our add contacts view when someone taps the add button what we want to do is we now want to call that function so let's do that now okay cool so now that we've done that let's actually review how this works in swift ui and how by using just simply published and observed objects so i'm just going to pin this so by simply just using um observable objects and publish we can easily pass data between our views and observe changes to them if i hit the plus button here we're now gonna basically get this new screen we can add a new contact so i'm gonna fill out some information and as you can see now we've actually basically got our item in our list so we basically got our list of items showing up because our contacts array isn't empty anymore it's now automatically observed that change and it's basically redrawn the view and it's now showing our list of items so you can see here how swift ui is really good with listening to changes and it's very very easy to basically observe changes as well so this is a really simple example so what we're going to do is we're actually going to move on to the next um section and actually see how we can actually create our own publishers from scratch and actually see how we can handle this in swift so let's do that now all right cool so what we're going to do now essentially is we're going to actually look at how we can actually build our own publishers so if you just open up the any publishers justin neville and if we just switch to that as well what we're going to do is we're basically going to create a function which basically has its own um publisher and we can observe the value that we get back from this api request here so the first thing we need to do is just type out the signature so let me just type this out and break it down for you all right cool so we basically got this function here but if you look at the return type it says any publisher so basically any publisher is essentially just a way of just creating a generic and publisher in general and we basically find that we want it to basically return an array of posts so this is the you know when it's finished and successful give us an array of posts and if it ever fails the error is going to be never so it's never going to fail so what we're actually going to do is when this api request fails we're basically going to essentially just return an array of empty posts so what we need to do now is actually to type out the code to call the network and then he called these posts and then give us the response back to basically have our polls so let's do that now all right cool so let's break this down so essentially what we've done here is you basically create a url session like we did in the previous um chapter where we basically downloaded an image from the internet and then the next thing that we're basically doing is we're basically going to call the service so using our url for to get our posts i'm going to map the data from our server so basically convert into data and we're going to basically use this high order function here called decode so what this decode function here is doing is it basically gets the data and decodes it to an array of posts using a json decoder so it's basically turning the json from a service into an array of posts now if this fails what we're going to do is we're basically going to catch any errors and just adjust return an array of empty poles so this just here this is going to give us an empty array of posts so because we define never here we'll just go basically this you know have an empty array of posts and it's very very important that you use this erase to any publisher so essentially what this does is it basically allows you to basically turn this publisher into like a generic and publisher because the signature from this and publisher is not going to match this so what this basically does it allows you to basically just convert into like an any um publisher so you can you can just return any type of publisher and then finally what we do is we just return at the end here so now what we need to do that we've got our own custom publisher is actually subscribe and actually listen to the value that we get back from the service so let's do that now cool so as you can see here the syntax is very very similar to what we've been using before so essentially all we're doing here is we're just basically getting from our publisher we're going to sync and just basically listen to the value that we receive from it and then we go print out the post and then we're going to store our publisher in our set of um constables so now let's run this and see what happens so if i just run this now and then just check the console you can now see that we basically get all the json but from the service and this was successful because it was able to successfully um call the server so you can see all the information here cool so as you can see we're basically able to easily just call our you know service and we're able to actually just create our own publisher here to essentially um you know subscribe to events within our code so what we're going to do next is we're actually going to take this a step further we're actually going to use um something called future and the third so it's not future like mask on mask off future but basically it's swift future which basically allows us to like take our you know combine to the next level and create essentially our own api and functions so let's look at how we can do that all right cool so like i said in a previous chapter um essentially what we're going to do now is basically take our publishers and create our own publishers book this time take it to the next level so what we basically have here is we basically have a screen um in the future and deferred so the future that deferred um xcode project here and what we're basically going to do is we're basically going to write our own custom publisher and that essentially tells us when someone's either accepted or and rejected giving us access to their push notifications so that's the whole point of this button and then this um status um unknown is essentially going to observe that change so what we're going to do now is we're going to basically create our viewmodel called notification view model and look at how we can use future and deferred to basically create our own combined um api so let's go into here and let's just create a new group called view model and then we'll go create a new um file called notification view model all right cool so in our notification view model what we're going to do is we're going to basically create a function that allows us to authorize a user using the user notifications frameworks so let's type this out and then break it down all right cool let's break this down so essentially what we've got here we've got a function called authorize which returns any publisher of type bool and error and essentially we've got this new kind of um like closures here called the third and future so what do these two do so essentially what the third actually does it basically allows you to basically wait for the um subscription to run before it actually allows the publisher to basically emit any values so if we didn't have deferred here when we call this function our future would actually automatically once this class is initialized to trigger essentially so this basically allows us to delay our actual publisher from emitting events until we actually need to so what future allows us to do is essentially what i just said before where it basically allows us to emit whether there's been a success or a failure so in our case on our publisher we defined that it's possible to basically get have a success of boolean and it's possible to have a failure with an error so our future is basically help us emit that success um which is either true or false and also there's a failure or emit the error and essentially what we do within our future is we basically call the users un users notification center we get the current notification center and just basically request authorization from that within our app so if there is an error then we're basically going to get the error and then essentially push that through with our future handler so push that event through with the arrow and if there isn't an error we're going to push through a success with the status of whether the notification has been granted or not all right cool so what we need to do now is we need to actually see how we can actually use this code within our actual view controller so we just go back to our view controller let's create an instance of it here and a subscription as well all right cool so now what we want to do is essentially want to actually see and subscribe and to the event that gets he made from our authorized and publisher so within the permission did touch let's actually write out some call to do that and then we'll discuss it all right cool so what we're basically doing here now is when someone taps our permission button we're basically going to call the authorized function and if we get an error from the authorization and you know publisher rather than showing that ever on the screen for now what was going to do is just replace the error with false so whenever there's an error we'll basically just basically say publish false then what we're going to do is we want to receive every bit onto the main thread now it's important that you do this because when you actually um run in and you're basically asking for permission to um the user's notification i think i'm pretty sure experience runs on the background thread and because we're going to update the ui we want to make sure that we update the ui on the main thread so that's why we're doing receive on the main thread and then what we're going to do is we're going to sync and basically receive our value from our publisher and update our permission text label here so if we basically do get our push notifications granted this will basically say you know granted and if we don't we deny it it will say denied and then finally we store our publisher in our you know set of cancer balls so we're gonna do now is we're going to rerun this now and then see this in action so we just run it so if i tap ask for permission you'll see that now it's actually asking me for permission so it's executing our code for the un um user notifications to to request authorization and if i choose allow you can now see that our label has now dated to granted and if i had to stop this and just run it again so if i actually need to i need to um delete it to see this change so if i just run it again from fresh and if i tap the button again i hit don't allow you can now see the label says that we've been denied which is exactly what we want you can see here how you can basically build your own like combined api um using deferred and future and any publisher and you can essentially cut down a lot of code and keep your code nice and clean now i want to give a little shout out to this tutorial in terms of like you inspired me for the future and deferred section because i feel like you know you get inspiration from somewhere you should always give a bit of you know give a bit of clout so i want to basically um give a big shout out to majid um who basically has a great blog on working with swift ui and using combine and whatnot so i'll leave a link to his site in the description box below if you want to go and visit yourself and i'd highly recommend you check out and subscribe to his newsletter as well to basically get updates and to see how we tackle swift ui and combine because it's really nice and clean so that's everything from to me today in this video and if you have any feedback or other suggestions please leave it below in the comment section below also as well i'd appreciate you give this video a thumbs up if you enjoyed it and also as well if you're not already subscribed to your channel to help the channel grow and hit the notification button updates whenever i release a new video so that's everything from me i'll catch you all in a bit deuces you
Info
Channel: tundsdev
Views: 8,367
Rating: undefined out of 5
Keywords: Combine framework, Combine framework tutorial, Combine framework example, Combine framework swift, Uikit combine framework, Combine framework uikit, Combine swiftui and uikit, Swift combine example, Swift combine tutorial, Swiftui combine, Combine swiftui, Swiftui combine framework, Combine framework swiftui, Combine framework swiftui tutorial, Getting started with combine framework, combine framework practical examples, Swiftui tutorial, Uikit tutorial, uikit, swiftui timer
Id: X2m0f2NoB10
Channel Id: undefined
Length: 92min 12sec (5532 seconds)
Published: Sun Apr 25 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.