Intro to Reactive Programming by Jordan Jozwiak of Google - CS50 Tech Talk

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone thanks for coming and welcome to this talk on reactive programming and rx tropi I'm Jordan I'm part of the Harvard class of 2014 I was a social studies concentrator of the CS secondary and I was a cs50 TF for three years but probably before most of you took the class and most importantly I lived in the best house Mather house I just want to get that out there okay post college I worked at double-dutch and Aero is an Android app developer and now I'm at Google working on the api's that helped control car functionality in Android auto okay so let's dive right in reactive programming is a programming paradigm that allows us to manipulate streams of data with functions and everything works asynchronously meaning that we don't have to wait for the result of operations but we'll talk more about this as we go okay so what is reactive programming really well it's an approach to problem solving and it focuses focuses on three aspects which were kind of conveyed in that sentence before one data streams so this is a flow of data objects that start somewhere and are consumed elsewhere functional programming and you're used to using functions and your normal style of like imperative programming and we'll get into that term later and so we use functions throughout programming but functional programming means using functions in a certain way and in this case we're talking about applying functions to manipulate a stream of data so for instance we might combine multiple streams of data together maybe we filter out some results we might manipulate the data in some way to transform it to something else functional programming is a kind of central focus topic for cs50 one so for those of you who are going to take that or will take it that this will maybe give you a little bit of a primer for it and the last part is asynchronous observers so unlike synchronous programming where one line of executes Waits until well we wait for one line to finish executing before the next line executes with asynchronous observers it means that our code has some some parts of our code will execute at different times in other parts so if you're familiar with like callbacks maybe you set like an onclicklistener for something and it calls back later that's asynchronous and with reactive with extinct earnest observers then we also have these callbacks that hipa happen later and we'll talk about all this more in a little bit so what are the actual applications of this well so for instance maybe we would want to retrieve data from a database filter out some results based on the user setting so one reason this would be a good example of reactive programming is because we have those few elements here so for instance we have a stream of data or some data coming out of a database and because it's from a database this is an operation that might take a little bit of time maybe we're making a request over a network or even just sometimes you know database queries can require some time with joining and looking up in multiple tables so because it takes a little bit of time we would want to avoid blocking other operations and it'd be a good case for handling this asynchronously we would also in this case want to manipulate our data by filtering out some results so we might have some sort of filter function that says we will exclude certain values some other examples might include rendering a UI that combines data from multiple data sources creating a real-time model of stock prices show an autocomplete search results for a user and maybe logging data from a temperature wind or pressure sensor in each of these cases there's some sort of data and an opportunity for functional manipulation of that data stream and they might benefit from being handled asynchronously so they could probably be handled without reactive programming as well but reactive programming makes these sort of problems easier to deal with and are there any questions on why these examples would kind of fall on the bucket that I'm talking about in terms of these three areas it's okay there were plenty of time for questions later okay we'll move on okay and the reactive programming isn't just theoretical people actually use it it's great for mobile development because there are many network requests that shouldn't block the UI so we're frequently getting data from some server manipulating it and showing it in the UI I know that Google uses it in some cases for data requests database requests and the reactive website which we'll get into this more in a little bit also has a number of lists a number of companies that use it I know Netflix was an early adopter and has written some blog posts on how it's helped them and reactive programming when I've talked about it so far it's kind of this theoretical idea we have these principles and reasons that we might want to approach programming in the certain way but many languages don't have these concepts built in so you may be like Java C it doesn't necessarily cater to this program this paradigm and way of solving problems in its own nature so we would need some sort of library that's an extension on the language itself and anyone could implement a reactive extension library but the most popular one is reactive X dot IO specification and that's one we'll be talking about today and examples and their implementations for a number of languages including Java Swift and JavaScript so I'll be focusing on rx Java today so let's go through an example of a data stream I've kind of tossed around this term a flow of data similar then submitted and we'll actually look at an example now so this line here represents a time line of events there are going to be data emitted data data will be admitted on this timeline of events and there have to be any data items for this stream to exist there could be nothing that ever happens kind of pointless but it could just be one or million they could be admitted at any time and no regular intervals so for instance suppose we have some imaginary data source that's emitting numbers and here it emits four to one seven six at kind of a regular interval and now with that data stream as these events were being emitted suppose that we had some function that could transform the data in some way so maybe this function is called filter and right here we have the function filter that takes an input X which would be any one of these individual values and it'll check if that value is even because X mod two equals zero we'll check if the values even and so this will return true or false depending on the input of each value so if we apply this upon this function to each data item only the even numbers will be in our output so for mod two equals zero this this is an even number two is also an even number one is not so no event would be admitted there seven is not but six is so that one would also be emitted and these data streams could live anywhere so for example this stream emitting the events could be some cloud application some server and maybe we're subscribing to the events on a phone and this could be like a mobile device rendering a UI and the technical terms here to describe the stream that's emitting events is called the subject so this is the one that's actually producing the events it could produce zero items one or Millions in this case it produces five and the stream at the end that's actually consuming the events is called the observer and we aren't limited to just one observer and this is one of the cool things about reactive programming is we can actually have multiple ones and I'll get into that a little bit so in this simple example to come back to now that we know these terms there's a subject emitting data a function manipulating the data in a in an observer consuming the output this idea is also similar to publish subscribe or pub/sub if you've heard that before it's technically called the observer pattern because we have a subject producing data and we can have multiple observers which is one of the Gang of Four patterns if you've heard of those before but no worries if you have and as I mentioned we could have multiple observers so this one maybe it uses the same function and this is just some other application may be a different element of the UI that's also taking in the same data input so in our example we used a function called filter but there are many commonly built-in functions to the reactive extension specification which should cover pretty much all your use cases so for instance there's also filter map count max min delay and they're probably pretty self-explanatory map if you haven't heard that term before is a way of saying that we want to transform a data into a different type of data or a different values so maybe we take in an integer and we return a string and that would be mapping data into something else so basically it's some function that takes some amount of time and a lot of these operations like filter that'd be a very fast operation but it'd be okay if we put in if we do some operation that would take a bit more time because as I mentioned these are asynchronous operations so our observer doesn't necessarily expect the data to be emitted quickly it'll handle it whenever it actually gets the result and remember that there's no regular interval for the data items emitted they could have been at totally different times and there might not have been any events and our data event doesn't need to be numbers it could be strings floats complex objects may be coordinates or may be some user data in this case characters and the data and that data is manipulated by some function that transforms the data it could even adjust the interval at which the data is output so for instance here maybe the data the observer doesn't see the exact same number of vents at the same time notice here that it's shifted a little bit and perhaps that's because there's some sort of like delay in to that particular item but we can basically do any sort of transformation we want and as I mention for the more there can be multiple functions that can change that can be chained together between the subject and the observer so you might ask like why do we need multiple functions can't you just have one function that does all the transformations that you need all at once well at the core of it it's because we don't want our functions to be too complex functions should do one thing and maybe to perform the final operation we want we want to do some combination of filtering out some values mapping some values and maybe you like grouping things these are all operations that we should think of those separately but we can change together and so maybe this is an example output okay and what creates the subject datastream because I've kind of been saying like the data comes from somewhere but something actually has to produce it with this idea of a stream in mine and these streams in arc Java are called observables and don't worry about this observable nomenclature it's more important that you kind of understand this high-level idea of reactive programming rather than the specific terms used in our extrav implemented but when these streams are created there's just some create method or some from iterable something that says we'll take in some input and start returning a stream and applying this sort of principle to existing object-oriented code can be a little messy sometimes so that's part of the reason that it's usually nice to kind of abstract that away and there are many open source projects out there that have many stars on github that just wrapped some existing library in an Rx library and then they're very popular for instance this one here is just a list of other rx libraries and it has 500 stars on github and kudos to that person who made it but I'm just saying it's there's there's a lot of interest in reactive programming out there and just sometimes applying this sort of clean abstracting this messy start away is really helpful and people appreciate it ok so hopefully now you understand high-level principles of reactive programming some applications for when we'd use it what a data stream is how a function can manipulate a data stream and how observers listen to asynchronous events and what that means and so we'll get into some more background and examples later but I do want to pause for questions here I know that's a lot and there's throughout a lot of terms so can I help clear anything up yeah Java has now just inherited that yeah that's a great point and I don't think I talked about this elsewhere so yeah in starting in Java 8 they added more functional aspects to Java and Java itself does have some streams one reason that it's still popular happens to be rx Java happens to be popular in the Android community is because a lot of that functionality isn't available but in addition to that streams in Java are pretty good but I think people have some concerns about them they could be easier to work with at least in terms of contained within the stream it might be fine but rx Java also here has the benefits of it has a little more flexibility in terms of the observer pattern it has some more options in terms of the threads that you can subscribe on so I would say it's just like kind of a next step yeah anything else yeah yeah I so I am NOT like a theorist in terms of the like what what a understanding all the programming paradigms and and how they relate to each other so I think that I know when I've read the reactive extension specifications they say this is not functional reactive programming that is something else but honestly I don't think I could clarify you what exactly that is but yeah we could talk afterward and feels okay well we'll just keep going then okay so before we go a little bit farther just some curious what languages are you all familiar with you can just shout it out and I know some of the languages you learn and CSF do so if you don't say those I'm going on to you okay nice Java good Swift of C++ Oh see ya there we go but what everyone should be learning okay oh so so some of the a lot of those languages mentioned are come from imperative or multi-paradigm paradigm Matic background and what that means is they usually involve some sort of conditional logic and state and we'll get into that more in a little bit some of these languages also have functional aspects to them and that's part of what makes them multi-paradigm addict so for instance Java now has functions built into the language and swift also has a lot of functional aspects and functional programming has a very steep learning curve I know that when I was first getting introduced to it it took a while to understand and our Java what I'm talking about today took even longer to understand on top of that so good for all of you for showing up today and grokking some of this no worries if it's a little difficult to follow that's also a little bit on me for presenting it so when I was learning this I was also I also asked myself why are there different language paradigms why isn't there one language that just works for everything and part of this is there are different use cases for programming there's you know it's just like a toolbox they're different tools that you have to pick the right one for the job but part of this is also kind of a organic immersion of ideas and so for instance even in linguistic languages there are differences in how people end up communicating so for instance grammatical structures and some languages I might say refer to my house is Jordans house and in other languages it might translate to be the house of Jordan there's also to kind of in Spanish you there are multiple tenses for the past tense there's a recurring past-tense in a finite one and not all words have the same sort of translation across languages you don't just have a single word and they're also dialects within a language so I kind of throw this out there as an example just to say that no in language there's no one language that is suitable for all purposes and also like we've all had similar life experiences globally but different languages have emerged and so in some ways that's similar to computer programming that languages are multi-faceted and but they also evolve over time so for instance imperative is one sort of language paradigm and that's probably what you've used for a lot of the languages you've worked with and reactive programming what we're talking about today is kind of a more specific per more specific programming paradigm but that's based on or partially inspired by functional programming which is used in reactive programming and I'll talk more about so I just tossed out these terms imperative functional imperative is as I was saying it's kind of based on state and conditions so let's kind of compare these and technically imperative and declarative are the comparison points here but what we'll use functional for simplicity so imperative programming we describe how the program operates and that means we have statements to change the state of the program we have conditional statements loops we might even have inheritance and these ideas of components that can be put together to create the whole piece it's usually an easier learning curve that's kind of an intuitive way to think about programs that you know there's some checkpoint that we understand this is the state we're in and then we manipulate it and some examples include C PHP and Java but I'm not trying to pick a fight with anyone if someone would argue that these languages are more multifaceted and this is a really simple example we have if value mod 2 checking if it's even we do something and here you can kind of see that we already have some idea of state there was a variable coming in and there's an if statement to manipulate something in functional programming we describe what the program should accomplish and that means it's ideally stateless and it's using functions that can create expressions instead of statements so we can change together functions that are ideally pure and meaning that they don't have any other side effects of changing state it's usually more difficult to understand conceptually because you don't have that idea of like where am I at right now and what are the components involved and some examples of languages that are pretty more strongly functional are skull and Haskell and honestly I haven't used either but I know some people who use them really love them and for example just this is just a function that could be used anywhere but it is I'm trying to convey here that we would have rather than maybe just have some sort of if statement checking and manipulating the data we could apply a function which would be used elsewhere ok and imperative programming originally a computer utilized vacuum tool tubes and had a limited memory they were written with step-by-step instructions including in Fortran which was introduced in 1954 and was the my understanding is is the first usage of compiled language with variables and complex expressions so in the past maybe is easy to understand especially in terms of how we use computers that we would kind of manipulate a state and iterate on that state and then there have been other languages since then and object-oriented programming really grew in the 1980s and we'll get back to that and so in functional programming it's based originally on the lambda calculus and also don't ask me about the nuances of that because I'm no mathematician but it's a at its core it's a study of computation with functions and the first functional programming language was Lisp which was developed by IBM in the 1950s and it stands for a list processor Lisp it's still in use today and it's only one year younger than Fortran so from the beginning there's already kind of a thought about different ways to approach these problems an imperative style and a function of functional style and back from nineteen back from the 70s there was this guy named John Backus who gave a lecture at the Turing Awards on why imperative programming is bad and functional programming is good and if you read about this online you'll see there are still a lot of people out there who pretty strongly believe that imperative programming is part of the reason we experience so many bugs in programming and that if we all just use functional programming we would have a better developer we would have better coding experience and we would encounter fewer problems in the real world and part of the reason that functional programming was didn't take off in popularity is just Java and object-oriented languages within cap in calculate encapsulation really dominated for through the 80s and lots but when JavaScript grew in popularity especially as a web language it is multi perdón perdón Matic language which makes use of passing around functions as first-class objects or first-class citizens and I think that's probably part of the reason that it functional programming has regrown in popularity okay so we have two programming we talked about these three areas of data streams functional programming and asynchronous observers so data streams it's the flow of data objects from one function to the next articulate immutable but that's a different discussion it's focusing the idea of objections change they should be stateless functional programming our example well I mentioned that functions are meant to be pure in our example we had a filter function that took in some input it happened to be an integer and it returned a boolean for whether the value should be included in the rest of our stream and it had no additional side effects the all its logic was contained to that particular function so for example we could also have an add function that takes in two values and returns the result and we'll also look a little bit later at a map function as I was mentioning that could may be taken an integer and return string it can transform the data and whichever way we want and with the asynchronous observers that uses the observer pattern with a subject for data sources that notify observers and one thing that I just want to mention it but we won't focus on much is that there are errors that can happen in these data streams and those are propagated through the whole flow of data so in normal well in the programming that you're familiar with maybe you like have some error checking at the beginning in Java maybe throw an exception and you have to handle that with these stream of data the error goes all the way through and it's up to the consumer to either handle it or ignore it and reactive programming is not its own language I mentioned on that it's a library that we apply to some languages like Java and it's also not react react jsr react native if you've heard of those those are some libraries that were made by Facebook and kind of focus on improving like UI development and mobile and web applications so we are extra I've mentioned is the one that the reactive library that I'm the most familiar with and so one will we'll be using our examples with two yet today it's pretty popular and I've used it in my own work for some side projects and at work as well the so this this specification was also applied to other languages like arks Jas and Swift and it is helpful do too complicated stream and asynchronous API so would otherwise exist in Java and it brings a functional design to a language that's traditionally object-oriented even though it has some more modern functional aspects and arcs Java is also very helpful for mobile development as I mentioned for Android an Android developers normally have to work within the constraints of Java 7 with some Java 8 functionality and so it's very helpful there ok so that's enough discussion of the background and history so let's look at some actual code maybe that'll help this all sink in a little bit more but before we move on any questions on any of this making sense so far yeah yeah because so in JavaScript which it's been a little while since I've worked with but you can pass a function right from like one thing to another and in Java everything has to be a class so when we pass a function we're actually passing a class which has an implementation of a function then JavaScript you can just pass like a function itself and so that's that's a way that it's so like in the argument of something you can pass in a function and and that's that's what I mean by first-class citizen anything else yeah yeah so state means and look at this in some examples later in a class you have some variables that might live outside of your particular function so maybe you're working on something and you know like at the top of your file maybe have some global variables maybe you also have something that like let's suppose we're making some game and we have some variable for like has game started and that's something that will kind of live there and we can access elsewhere in our code and that's some state and so when we talk about stateless that would mean we somehow eliminate all those problems that there is no external state that will be like reading it and that every all the data that we care about lives within or data stream okay so suppose we want to observe some data we'll use this term subscribe to mean observe the final result of a data stream and here I want to we'll get into comparing the imperative approach and the reactive approach and so we'll look at the imperative approach here maybe this is something that would look somewhat familiar we have some data source we'll get the data it's a list if you're not familiar with Java this is kind of like an array and it means that we have integer types here or like int types so we have some list of data and a for loop we'll just go through all of it and we'll print it out and this is how we might take some data and take some action on it and so for example our data input here could be 41 7 6 and we print out 4 - 1 7 6 so that's the data source and we print out the values and because we're using a for loop that's one of the signs that this might be an imperative approach now let's look at the reactive solution so know already that instead of getting a list of data we have a stream of data remember our subject and observe here our subject and observer from earlier well this data source is our subject technically this is returning an observable and rxjava but again I don't want to get caught up in the nomenclature so we'll just see that it has some data stream and our data stream has this built-in function called subscribe this is p'tee this is part of the functionality that comes with using the reactive X library and the SUBSCRIBE method takes in an observer so this means we're done transforming our data and we want to do something with it of course we don't have any transformations at this time but we will in the next example so the observer technically takes in a class called a consumer but this is what I was actually getting to earlier when we were talking about the first-class citizens for languages where functions are first class citizens and Java at least Java 7 and earlier we always have to pass in some class which has an implementation of a function so we'll get rid of this in a second and then we don't have to worry about this name called consumer and this is the function that the anonymous class actually implements and again we'll get rid of that in a second and the important thing is that this method takes in an individual value from the data stream called value integer value and it does whatever it wants with it so in this case it just prints it out and so to simplify this expression we'll use something called a lambda and Java don't worry about the name if you're not familiar with Java but see now that we can kind of clean up this is this is what you might think of this passing in a function as an argument so here we just have the input and we take some action on it the arrow means that we're expressing a function so the argument value is on the left the body of the function is on the right and the code does the same thing as that previous consumer class but this is easier to understand we can also use a method reference here but that's a Java thing and don't worry about it so these are the imperative and reactive ways to print out a list of data in the imperative case we get all the data at once and we use a for loop to print it out in the reactive case we get a data stream and we observe each item and in each case we would print out 41 76 and we can do more than print out our values that's just an example we could maybe update a UI with these values or maybe save to a database reactive programming is an approach as many applications so we can't we can kind of do whatever you want with this so now let's talk about a scenario that definitely merits a reactive approach suppose we want to get all data changes from a data source so we want to observe the changes in Java there might be simpler ways to do this but this is one that I as a solution and it's kind of long and complicated involve some threads for scheduling updates to listen for data changes and honestly I I don't I don't even understand how that works basically it's complicated and there's a better way so here's the reactive approach does it look familiar it's the same as the other example why well our data source is already a stream so there's a base assumption that the subject emitting date events will notify us if all changes that's what it was doing the whole time every time we got a data event we would have it emitted there so our observer will be called for all data changes going forward for the first one for the second one until we decide to stop listening to data okay and any questions on that before I move on the SUBSCRIBE idea data changes make sense to data and so on and so forth hmm where's the one on the right it's like Oh magic happens and I know that there's new data and I can act upon yeah there's a lot of sort of framework that has to be surrounded right true true and that's that's why earlier on I was kind of mentioning that the subject of getting that data stream there's there's a lot of work that goes in there and so you're right that in some ways this isn't a fair example because this code might still something like this code might have to live somewhere else in how we create the data stream yeah and that that is kind of up to the implementation of that so there's there's a little bit of in some of these examples when I especially when I portray reactive programming is the great way of doing things you do have to keep in mind that somewhere behind the scenes there might be something messy going on anything else yeah yeah yeah they're assuming we don't want to get multiple instances of the data stream we could have saved this as a variable and which maybe then we're getting into some like imperative approach but we can talk about that later so we save this as variable and we subscribe to it and we could just have another thing right here for the same or I mean we could just skip the data stream again kind of depends on what this reference is but then we can just say subscribe and another one and take some other action on it yeah no that's the terminal call yeah but there is this idea of do on next so we could have multiple things that happen for each event and then you could just subscribe without any action which means start start doing everything I said to do so you could chain multiple do on next and then have that subscription start but if we want them totally independent then they probably should be different subscriptions kind of depends on whether there might be an order to the tassle we want to accomplish anything else okay so now let's actually apply a function to our data stream I mentioned filter a few times so we use that as our example in the imperative approach we will do pretty similar to what we did before but now we include this if statement to only act only print out the even values because again this value want to equals equals zero we'll check if a value is even and so rather than four to one seven six will print out four to six this I kind of showed an example of this before when I had the animations this is an actual image from the reactive spec and we call these marble diagrams because there are these like little circles that might resemble marbles and some of them make it through some other ones don't so rather than use that if statement we could think of that check is a function which we could always just write that function separately as and use it as an imperative way we're gonna think about it in terms of manipulating a data stream so similar to the timeline and data events from the beginning this marble diagram shows how we could filter based on values greater than 10 but in our example we're going to filter based on even numbers so this is this is the reactive code and here we'll apply a function called filter which is takes a value takes the value from each item in the data stream as the input and if it checks it that and it checks if the value is even and implicitly there returns true or false value montz you equal equals equals zero or return true or false and this boolean result is used within the internals of the filter mechanism to limit which items are passed through to the rest of the data stream so again like the implementation a filter might well it's probably fairly straightforward but it could always have something that maybe looks like this under the hood and filtering is an interesting example because it restricts which items are emitted into the rest of the stream but suppose we wanted to change all values in a consistent way so if we were to for instance double all the values on our stream we might take a reactive or an imperative protest we don't have to save a temporary value here but we just multiply the value by two and print out the result but again we could think about this as a way of manipulating a data stream and will apply some function called map this example marble diagram has all the values multiplied by ten and so the reactive code looks like this pretty similar instead of the filter function we have a map function which is also one of the built-in functions to the reactive reactive extensions library and it takes each value from the stream as input we calculate the new value in this case multiplying it by two and the result of that expression is implicitly returned and then we subscribe to the results in print event okay last example this one is maybe a little more complicated and so I just want to show maybe one of the times or reactive programming could save a little bit of trouble so this is the imperative code for grouping some data and there are a number of different ways to do this this is just one example at a high level we'll just kind of gloss over this we scan through each item in the list put it into a map with the appropriate key for even or odd and and then we'll print out the results at the end so loop through each value you find out what the key is put in the value into the key this code is fine it works but there are also some sort of like different functions and tasks involved there's some maybe like grouping here based on different values there's looping the keys are some variables that are used outside of the loop and so in some ways you might say that this code is like a little muddled together and we could definitely clean it up an imperative way but we can also think about it maybe as kind of a if we have the stream of data and we really want to separate these streams we could group by this use a function called group by and separate our original stream into two different ones and since this since grouping is an important part of data processing of course it's built into the reactive specification so the reactive solution looks like this we start with our data stream we apply a grouping function that will create the name for each group so if the value is even then we'll return the string even and if it's odd we'll return the string odd and that is going to be used as our key for the rest of the stream and I am cheating a little bit here the collect into function which is also built-in and is a way of kind of merging the result of a stream this ends up still looking a little messy kind of because we're putting a stream back into some stateful well into some object so kind of gloss over that but keep in mind that the grouping part there is pretty easy so there are a lot of examples there been a lot of examples to get us here but hopefully this gives you a glimpse into how reactive programming can simplify the approach for certain problems and there are many more operators we talked about filter map and group by but here are some of the other ones many are self-explanatory and their name hopefully they make sense I think a really powerful one that's especially helpful in mobile craft programming is called debounce which means if the users typing for instance in a search field we would we wouldn't want to show them all to complete we want to show them autocomplete results but not for every new character they search right especially if that's something that maybe involves querying some server we don't want send 20 server requests if they type a 20 character query so debouncing allows us to set a window of time where we listen for changes and then take action on the most recent one so if the user is typing really fast but then they pause then we'll show results for that and this is again something that under the hood may be a little messy but because we're using the reactive extensions library debounce is just built-in and if if this all seems complicated it is it's hard to learn it takes a little while getting used to even when I thought I understood rxjava and reactive programming I look at a diagram like this and stare blankly to be honest I still don't really know what this is saying I'm not sure why red circle comma cloud equals red cloud but yeah so if you become an expert and reactive programming an Rx Java please explain this to me but this is this is one of the examples for the operator join okay so we start at theoretical then we looked at some code examples with actual functions and so now I want to do a quick demo to really emphasize how powerful our Java can be but first before we dive into that any questions on any of the examples or still what is a data stream what am I talking about anything okay they also be question time for questions at the end so I'm just going to mirror my displays now okay so I made this I have been an Android developer so I thought it might be fitting to use an Android app is a quick example I shouldn't see similar ok so I made a little Android app here that is hopefully going to run there we go so I get for setting it to be five seconds so what this is this little app here is ticking in it's using a flaky temperature sensor a flaky wind sensor and it's showing us the current temperature current temperature wind speed and then what it feels like and these are like fake temperatures they're just generating some random values within a somewhat appropriate range and the reason it's there called flaky temperature sensor and wind sensor is because sometimes as you might have noticed here they return the value negative one which is just because there are some cheap hypothetical cheap sensors that don't always return useful values and in this I'm using the term presenter here is just some way of taking in these values and updating our UI we have a sensor view which allows us to set the temperature wind and feels like speeds that or values that we see there and this presenter when it starts it's going to add a listener this is probably applies across some multiple languages in Java note that we have this anonymous class here which it's telling me it could be simplified to a lambda but I just want to put in the whole anonymous classes the example so we take our temperature sensor we add some listener and it's going to keep track of the last temperature value the last wind value for the wind sensor and then whenever one of those is updated it's going to say handle values updated and so notice already here that because you can see I with the feels-like temperature it's actually combining the values of the temperature and the wind speed and calculating some other type of some other temperature value so that's why we are keeping these as some state and to get back into that original that comment about State and stateless this is an example of having some state in a class these are some values that are living kind of outside of any function for some reason they're in this class maybe they shouldn't be but this is one implementation and so we're listening to these values and an our handle values updated function here first of all we check if we don't have a temperature value or a wind value then we're just not going to do anything because when I calculate the feels-like temperature I need both values and they're both initially going to be null so this is way of saying we're just ignoring this stuff at the beginning then we're going to show the raw values in the view the temperature value in the wind value and then I also mentioned that these are flaky sensors right so we're gonna ignore the negative one values and so we have some conditions here all just to kind of get set up and then we're converting a Celsius temperature to a Fahrenheit temperature we have some function for that and then we're calculating the feels-like temperature based on the Fahrenheit temperature and the wind value and then we're finally setting the value so in order to accomplish this we had some state which lives in our class we have some conditional checks and we have some functions that are transforming some data and you look at this and you say like well this accomplishes what I want but in some ways it's a little imperfect and so I'll just kind of go through this reactive example so I'll try to go through this kind of quickly yeah sorry if if any of you have to go somewhere you're free to leave okay so if suppose maybe we have our temperature sensor and instead of getting setting or call back we'll get the data stream and this will be our temperature stream and this happens to be an observable and for wind sensor we'll get our wind stream and so now we're already subscribing to all changes in the data and if we want to actually print out these values like the raw values as we were doing in the imperative approach now we can do one subscription to them so for instance in the temperature stream we can subscribe and for each value we will set the temperature so here we have one subscription and for the wind one we can also set the wind value and so if I just change to use our reactive presenter and run this we won't get the feels-like temperatures but feels like temperature yet but we will get the other values okay and so now what the feels-like temperature we wanted to actually filter out some values and convert a Celsius temperature to Fahrenheit so another function that we have with our reactive observables is combined latest and this will allow us to take two different streams and combine them together so for instance with our temperature stream we can first will filter out the values that we don't want which will be all non-negative value or all negative one values and we also want to convert the values to Fahrenheit and we'll still use that that help our function we had before for converting and then we'll also use our windstream and filter out the values that we don't want which is the negative one values and then lastly we have to combine these two streams together so if we have a temp wind we can use some function on them calc the we can calculate the feels-like temperature and lastly actually subscribe to all this with whatever the feels-like value is so now if we run this oops oh thanks now we also calculate the feels-like temperature so remember in the other example we had some callbacks we were listening to some data values we had some state for the last values some conditional checks and here this is an example where we have two subscriptions we just show the raw values here with the observable but separately we also use this combination function combined latest which is taking these two different streams merging them together with this function where we have temperature and wind the temperature and wind and we calculate the feels-like temperature on that and then we subscribe to this particular value and set it on the view any questions on that okay so to wrap up reactive programming has data streams functional programming and asynchronous observers when would you use it well you'd use it when you're dealing with some of these things when you're working with streams of data or you want to notify some set of things asynchronously and so I like to thank you all for coming I know this went a little long so thanks for sticking around Thank You Rhine for organizing the cs50 staff for having me and for all of you for showing up and learning about something that is maybe kind of different from what you normally do I'll be around afterward to answer any questions so thank you [Applause]
Info
Channel: CS50
Views: 39,147
Rating: 4.8658681 out of 5
Keywords: cs50, harvard, computer, science, david, j., malan
Id: KOjC3RhwKU4
Channel Id: undefined
Length: 58min 16sec (3496 seconds)
Published: Tue Oct 02 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.