Going Reactive with Reactive Extensions & UI

>> All right. I’m very excited to introduce the next speaker It’s Rodney who will tell us about going to React with React Extensions and UI. So Rodney >> How you doing? Welcome to.NET Conf Today we’ll be talking a little bit about going reactive with Reactive Extensions in ReactiveUI So let me load my presentation and share my screen, sharing my desktop, sharing the PowerPoint, and off we go So I am a maintainer of ReactiveUI I’m sorry, going reactive. So I’m Rodney I’m a maintainer of ReactiveUI I’m a.NET Foundation member and I’m a Microsoft MVP Today I’ll be talking to you about going reactive with Reactive Extensions, ReactiveUI, and why you would want to use that in a mobile application I’m going to start with a brief history lesson, some concerns that mobile developers face A little bit of a demo, a shameless plug and give you some takeaways at the end I am sharing. It says “Share Desktop”, hold on, desktop, all right, now can we see my screen? Okay, and you can hear me now too, yes? All right, wonderful So I won’t bore you again, but I’m Rodney That’s me. Here we go So in 2007,.NET 3.5 landed, and with it brought link language integrated queries That was C#, first step towards adding functional elements to the language It allowed SQL style functions to be parsed over collections like objects, SQL, and XML 2009, Rx.NET was created, Erik Meijer and Wes Dyer pretty much broke the world While working at Microsoft they stumbled upon a monad and they realized that if there were pull-based collections, that there had to be push-based collections In 2010, [inaudible] created some extension methods using Reactive Extensions for MVVM and.NET applications So the interfaces that you see are first-class citizens in the NET space, right? On the right, you see your IEnumerable and your IEnumerable, and on the left you see IObservable and IObserver When you traverse a list in.NET, you are using the IEnumerator interface to get the current node, to move to the next node, or to reset to the initial position of the list That creates a pull-based collection It pulls in a certain amount of data and doesn’t change unless you explicitly mutated If you’ve ever seen the yellow squiggly that says multiple possible enumerations, this happens because the enumerator could reset once the list mutates If you’re not explicitly to listing, you’ll end up starting back at the beginning of the list and having extra traverses on the list IObservable is a push-based collection This works well with technologies like [inaudible] real-time events, and asynchronous programming The observable allows you to subscribe, which basically allows any observer of the observable to process and read values from that list An observable is really a collection of things over a span of time You’d have OnCompleted, which is a notification that lets you know that there are no more elements coming on the list OnError, so if the list errors in the middle of processing, you’ll be able to catch the error and handle it accordingly, and OnNext, where you can explicitly act on whatever the next value is on the list I want to point out that this is similar to the Gang of Four publish-subscribe pattern A great example of an observable is a Twitter stream You have many people watching the stream You have stream constantly updating and pushing new data to it All subscribers have the opportunity to act on any value pushed to that stream So I know most people think that Reactive Extensions is this evil wizardry I will tell you that I’ve had people look at the code and say it looks like magic I’ll tell you, I agree,

it is magic, but it’s composable You can compose parts of queries the same way you could do with an IEnumerable and branch various observers to do different things at different positions in the query execution It’s declarative, so you declare what the code should do and it will just do it It’s reactive, when the state changes, the code will just fire off, and it’s readable It’s very human-readable because it uses link operators, Reactive Extensions themselves are across a lot of different languages; Java, Go, Swift, JavaScript, Kotlin, and PHP Even PHP uses Reactive Extensions But Reactive Extensions is really all about collections So I’ve got a quick video that I want to play that explains what I want or what I think Reactive Extensions are I know that there’s no audio for this video, but this is a very good point I’ll go ahead and pause because we’ve just errored, as you can see We’ve hit the OnError condition In this example, the conveyor belt is basically the observable It’s a collection of things that are happening over time The chocolates represent events or tasks that are happening Lucy is an observer of that observable She’s able to pick chocolates off the conveyor belt and act on them She’s able to put them back on the conveyor belt, and this is a great example to me because events happen fast We need to respond fast, and maybe we need to group the events, maybe we need to batch the events, and maybe we need multiple people observing the events in order for them to be successful So what’s this have to do with Xamarin and mobile? As mobile developers, we respond to events We’re constantly using the commanding pattern to create event handlers that will do work in our view models We’re trying to avoid memory leaks We have limited resources We have a managed run time that we have to deal with in Xamarin and iOS, as many of us probably have already seen, will crash your application if you exhaust the memory that’s available It’s also recommended that we use Xamarin Profiler before every release But let’s be honest. Who does that? You just wait for the editor will crash and then you go look for logs and try and scrambling to figure out what’s going on so you can push an update to your application Asynchronously loading data, we need to load data when the page loads, because unlike Web, there is no global application state So when the page loads, we need to call out to an API and get more data We have to handle disconnected state, no Internet, no problem Your application still has to function and it still has to work in a disconnected state You as the developer have to respond to that state change So how many have ever seen this? This is a basic Xamarin search bar with a text changed event handler, and we’re providing it some delegate The problem with is, is that the delegate isn’t cached So if the delegate isn’t cached, you can’t properly dispose of the delegate Because there is no explicit reference in memory to the delegate the garbage collector won’t recreating that memory So what happens? It leads to memory leaks The three main things that I think developers need when handling events are event handlers, which are basically callbacks Callbacks, you can do separately if you want to, and then deallocation I think deallocation is the thing that we struggled with most because it’s a question of how do we properly dispose of objects So what if I told you that this is basically link over an event stream System.Reactive provides a way to convert events to observables This is effectively link over events, just like you would have link over objects, just like you would have link over AI innumerable, you can have link over in AI observable This particular code sample will delay the processing on a set of events It will process this off the main thread, which is important for Xamarin developers because if we do too much processing on the main thread, the main thread will lock and our application will crash It allows us to select the state, only select state that has changed, verify that there is an actual value to process We’re also telling the code to return

to the main thread when we’re done executing, we can invoke a delegate, and then we can easily dispose of this entire process when we clean up our view bindings So let’s look at some code That’s not the right one. There we go Let’s close that down and look at some code So first I’ll talk about what you do in a non-reactive scenario In a non-reactive scenario, you would create some search bar, which is just a Xamarin Forms search bar with a text changed event and you would give it some hopefully cached delegate Then you would have to explicitly dispose of that cash delegate at some point in the future using the dispose method, standard IDisposable The problem comes in with this delegate itself If you’ll notice, we are responding to every single text changed event that happens during execution, which means every time the user of your application types in a letter, we have to then go execute our search command This can become process intensive, it can lead to too much HTTP traffic over a very small pipe, and it doesn’t lend to great user experience Now you can write your own code around it and write a buffer and do all and all of these things, but that’s additional code that you have to maintain and hopefully unit test But in a reactive scenario, I can take my event, my text change event, and wrap it in an observable So the Systems.Reactive allows us to take an observable from an event, provide an event handler, allocate and deallocate memory all in one succinct block of code So now again, I said earlier that observables are composable, I’ve now composed an observable of text changed event arcs I’m again going to, let’s see if we can do that Think it’s control I’m hitting the Command Plus and it’s not doing the thing Let’s just go ahead and go to preferences and bulk farm, which I had it’s said So let’s look at where’s font text editor, general, key bindings Key bindings, fonts So let’s set to the font size 18, see if that works better I guess not. Let’s try 24 then Is that better? Hopefully So that’s better Good. So again, what we’re doing is throttling and saying we only want to process events 750 milliseconds after the user stops typing We explicitly want to look at these events on a different thread than the main thread We’re selecting, we’re explicitly making sure that it’s distinct in that it won’t change, we’re selecting it, out and then we’re processing it So let’s go ahead and run this code That way I can show you that it’s not really magic, it’s just a different way to look at programming Good stuff. So I have a standard search bar and this is plugged up to a doc.go implementation so I can get information from the web So I’ll go ahead and start typing in Xamarin As you see, I’ll execute the search query Well, there we go Now it’s doing special things I’ll execute the query. It’ll happen twice, but there’s a reason for that, which I’ll get to it later, and you’ll see that I’ve got a list of responses Now I want to point out that again, I said there’s a distinct until change on it So if I go back and hit n again, you’ll notice that the search query doesn’t get executed again But to prove that I’m not a liar, I’ll fat-finger it and now you’ll see that the query execution is actually happening again Now it shouldn’t provide any actual values, but this shows that we can defer execution of events that happen from our UI toolkit being Xamarin and not have to process everything

We can use link that we know and love and had been using since 2007 to functionally react to code, or better yet, functionally react to what the user is providing us So I’ll go ahead and change it again so we can watch the search query execute I’ll go back to the code again because I want to point out a couple of things A lot of people will say, and I say myself, that this is a lot of boilerplate code and I agree with you 100 percent So the reason why my search query was running twice is because of this chunk of code right here This is an actual X name to the search bar in my XAML, and I am using a package called Pharmacist, which is under the reactive UI umbrella, it was created by Glyn Watson about a year or so ago, and what it does is takes all of this boilerplate code that it takes in order to wrap events and does it for you So anything in the Xamarin UI toolkit that has an event gets wrapped using this events So all I had to do is name my element, look at the events on it, and then I get an observable, that is the text change events for that particular UI element This cuts down on a lot of time It cuts down on a lot writing a lot of boilerplate code and makes it very simple to start getting in and using linked to events So we’ll go ahead and go back So the other thing that observables are Observables are asynchronous, they are awaitable, you can use the asynchronous syntax, they can be scheduled on specific threads So not just configure await false, we can actually say, use it on the task pool scheduler, do it on the immediate scheduler, do this on the UI thread, and they just emit values over time asynchronously They are awaitable, like I said, because you can actually use it with the TPL that you’re used to So the async and await operators are valid with observables Observables, they return IDisposable IDisposable is important because it allows us to clean up resources Again, we’re trying to prevent memory leaks The Reactive Extensions provide a way to model asynchronous programming and dispose of their resources very cleanly in a way that the task parallel library does not But you can use it with the task parallel library, and if you’ve been programming as long as I have, you remember the old wild wild west where you had callbacks in commands and delegates all over radio code and you didn’t know where anything was or what was going on and it was very spaghetti So as a Xamarin developer, how many times have you had to load data asynchronously or load data when the page of the ViewModel is created or load data to a ListView? ReactiveUI has an interesting story for loading data There’s no need for async void in your constructor It’s bad, don’t use it There’s no need for doing any type of asynchronous programming in your constructor We can actually load data in response to the ViewModels initialization Further, I’ll say the dynamic data has an interesting story for ViewModel creation It provides lists and dictionary style collections, and dynamic data is another library in our ecosystem It allows you to propagate changes from the list as a set of chain sets It has standard link operators and it also has some custom filter and transform operators Candidly, dynamic data is everything I wanted observable collection to be, but it just never really panned out So let’s go look at some more code First, I want to pull up what you normally see, at least what I’ve seen in a lot of Xamarin applications that I’ve inherited, things that I did before I found Reactive Extensions or ReactiveUI, but I did this, which is very common I use async void because task return type will immediately cause type issues and this works, but there’s a problem Async void is not actually good for our code because void is the absence of a return type, and the TPL doesn’t actually give us an aggregation of the errors in the event that

the task fails somewhere along the way So an alternative way is this code right here What I’m basically doing here is using ReactiveUI, one of the extension methods that was originally created as part of the library, and I’m saying when there’s a value in the ViewModel So anytime that the ViewModel has a value and the ViewModels not null, I’m going to explicitly change it out to a notification Because all I want is a notification that it’s happening, I don’t actually want to process on the change itself I’m going to look at it on the main thread and I’m going to invoke a command, and then again I’m going to dispose it with my nice view disposal bindings So what this does is allows us to lift the concern of creating an asynchronous task in our constructor, and when the view loads and it creates its binding context, it will then go and generate the call and get the data This is an extremely useful use case, it’s probably one of the use cases that attracted me to Reactive Extensions and ReactiveUI because I was doing a lot of async void and then I read the async void is bad, and I had no idea how to do it because constructors don’t allow for asynchronous methods and I wanted a way to load the data when the ViewModel is loading So I’m going to segue into pointing out that this data load is basically just an implementation of a signal art connection Hub I don’t have it wired up to an actual connection right now because demos are hard and I didn’t want to accidentally break the world But you can see here in this class that the mock that I have is going to respect the exact same interface for abstract class What I’m going to do here in a real scenario is I’m going to connect using the connection string I’m going to create my hub builder with that connection string and whenever a value is pushed to me from signal R, I’m going to add it to my dynamic data cache But the way I’m going to do it is a little bit off I’m not exactly going to put it directly into my cache because again, I’m trying to separate my concerns I’m using a subject which is both I observer and I observable and I’m going to push data onto my stream using the onNext method that we saw earlier So effectively what I’m going to do is anytime something gets pushed from signal R, I’m just going to take a new value of my observable This is asynchronous and it’s relatively easy to set up So let’s go look at the ViewModel itself The ViewModel is going to have an injected I order service, which is going to have a connection Hub client in it, and all I’m going to do is look at my observable cache, which is the dictionary implementation in dynamic data and I’m going to connect, publishing rough count, which these things are beyond the scope of this talk I’ve got a blog post somewhere where talks about these things Then I’m just going to transform my BTO to my ListView item, and this is very clean and very straightforward, versus some of the code that I’ve seen in my past where I’ve got a function and in the middle of the function, I’m newing up some and data and I’m newing up a ViewModel but only certain times What this does is allows us to react to the fact that values are being pushed to us and then transform those values and display them on screen I’m going to bind out to a read-only observable collection, which is just a fancy observable collection which is been bound to my view and everything is going to be great So let’s go ahead and run this code See that’s non reactive so let’s close that and let’s execute thing So the usual business domain that I use for demonstrations and code samples is coffee, because I drink a lot of coffee and I like coffee So what you’ll see here is basically just a list of orders that are being generated from a mock that are being pushed to my code As you see, the ViewModel is or just updating So every time a value is pushed to the source cache, I’m basically transforming it out It’s getting bound out to my read only observable collection and automatically getting populated in my ListView

So I’ve got it set right now to push me one, maybe every 750 milliseconds But you can imagine using something like this for any type of signal or any type of real-time inventing, any type of processing where you are going to be getting a stream of values that you need to process Let’s go back over here So we get to the part where I’m going to do some shameless plugging This is the ReactiveUI team We are part of the.NET Foundation There’s some alumni team down at the bottom, as you can see, people who I’ve learned from and continue to learn from But what I want to talk about is where we can actually be used We have packages that are usable in Xamarin.Forms We actually wrap Xamarin.Essentials, Xamarin.Android, Xamarin.IOS, Xamarin Mac, Tizen We even actually have Blazer Support So we are found in any place that you would want to use Xamarin To develop a mobile app, you can use ReactiveUI If you want to do it at a Xamarin Android level and you want to do a Xamarin Android project, ReactiveUI can support you If you want to do Xamarin Mac, ReactiveUI can support you So now I’ll talk about some of the shameless plugging and some of the takeaways So ReactiveUI is just MVVM niceties on top of your UI Toolkit Most of the magic comes from Reactive Extensions A better understanding of Reactive Extensions will help your understanding of how to get more value out of ReactiveUI Pharmacist, which is the logo on the left, is a clean way to cut down on boiler-plates so that you can link two events and wrap and dispose of your Event Handlers easily and cleanly It works at Compile Time So you have all of the niceties around Compile Time, and it’s a very simple way to get started with Reactive Extensions Dynamic Data, again, it’s what I thought Observable Collection should have been when I first started It allows for encapsulation of the Data Logic So you can actually lift a lot of your Data Logic out of your ViewModel and put it into service and just allow Dynamic Data to present the data to your ViewModel It will clean up a lot of code, it’ll make things a lot more testable and a lot easier for you to deal with Some of the main things that I see when people approach Reactive Extensions and ReactiveUI is that they want to use ReactiveUI without actually adopting Reactive Programming You can do this, but you would be leaving a lot of value on the table People won’t approach it because it’s functional, and functional has a very negative connotation in the.Net space But the main thing I see is, once people understand that it’s really just link over events and they start using it and see the power of it, they won’t want to do anything else The biggest misunderstandings that I see about ReactiveUI is ReactiveUI is not React, it’s not React JS, ReactiveUI is just extension methods on top of.Net Reactive Extensions so that you can have MVVM niceties You can use as much or as little as you want We work well with a lot of the other major MVVM frameworks because it’s a very much play as you pay model, where you can just take the parts you need and leave the rest behind You can use ReactiveUI without using Reactive Extensions Furthermore, you can use Reactive Extensions without actually consuming ReactiveUI But again, from MVVM perspective, it makes it a lot easier to deal with things The main difficult change that I see for people when they get started with Reactive programming is the fact that we define all of our logic in the constructor People say that they want clean, human-readable code Well, what better way than to encapsulate all of your business logic directly in your constructor? It gives you a single source of truth, you don’t have handlers here and callbacks there, and region tags to help clean everything up, everything’s in the constructor You are creating composable bits that will react to state changes as opposed to you having to imperatively change that state There’s a book called You, I, and ReactiveUI that was written by one of our alumni maintainers In it, is a lot of valuable information around how to get started with Reactive Extensions or ReactiveUI A lot of different scenarios and code samples are

provided around how you would do things like create a timer or change view components based on events or run animations based on events We exist in a Slack channel, reactiveuI.net/slask So if you want to get involved, if you want to see what this is about, if you want to get started using link to events and understand what power you can wield using this paradigm, I recommend you coming, join the channel, ask your questions, and we will do our absolute best to help you But the main takeaways that I have for you are using Dynamic Data to load data in transform can clean up your view models a lot Using Pharmacist to generate the events can reduce a lot of your boilerplate code when you’re trying to react to events Honestly, I would say don’t fear observables, just understand that it’s just another way to do link over a different collection type and you can use it to get started down this functional path It’s very much like Pringles Once you start, the fun doesn’t stop So I am done. Ready for questions >> How do you guys like ReactiveUI? >> ReactiveUI, yeah. Right >> Pretty good questions >> All right. Rodney, thank you so much for the talk, and we have feedback that that was a nice presentation Now I really need to play around with ReactiveUI So great job Yeah, that came from xsegno We have a few great questions So the first one is from Jean-Marie and the question is, ReactiveUI seems great for that search example But is it really useful in most of the apps when 95 percent of your screens are loaded just once, when you have so few updates messages? >> That’s a great question It isn’t as useful when you aren’t doing a lot of eventing But I’ve seen a lot of people and a lot of programs use a lot of events The average Xamarin screen that I see has anywhere between 5-10 events and event handlers So if you’re doing event intensive programming, I would say Reactive Extensions and ReactiveUI provides a lot of value If you don’t have as many events and you don’t need to respond to events as often, then it may not provide as much value to you >> All right, great Then next question is from Scott Baker He would like to know what is the difference between LINQ’s select and ReactiveUI’s Transform methods? >> So that’s actually a Dynamic Data extension There’s not a lot of difference, it’s really just a library specific way to do the transform So you could do the same thing using select, but we use it internal to Dynamic Data because there’s some additional niceties that happen under the hood So if you find me in Slack, we can look at those code samples and we can talk through that a little bit more if you’d like >> I see. All right The next question we have from Ishy Birthday The question is, what kind of design patterns are you using? So people are curious about different design patterns Can you give any suggestions on that area? >> So design patterns like Gang of Four Design Patterns, I’m really more following solid here, where I’m injecting a service into my ViewModel That service happens to just provide data So this isn’t probably what I would consider a known pattern, this is a pattern that I’ve started to evolve in other people I know in the Reactive community have started to evolve around Dynamic Data Because of the way it works, I can actually, instead of injecting my data service into or injecting my database call into my ViewModel and getting data out of the database, I can wrap that in a service and lift that work out of the ViewModel and just allow the service to provide me an aggregation of data So I’m taking the concerns of calling the database or calling the API or doing any of that work out of my ViewModel, putting it in a service and then allowing that service to propagate data to my ViewModel, because really the only thing my ViewModel cares about is data

>> Excellent. Thank you, Rodney All right, thanks for your great talk and excellent answers Now we’re going to make a five-minute break so everyone can grab lunch or relax a little and we’ll be back with you in five minutes. Thank you >> Okay