Xamarin In Action - Chapters 4 + 5
That’s right everyone, I am back with yet another post about Xamarin in Action. It has only been a few days since I released the last post but something big has happened in that time. Manning Publications, the publisher of the book have seen my posts and decided to share them on Twitter, wow!
I am really pleased to know people are enjoying reading them. To be honest I started the series because I am absolutely loving the book and wanted a place to express that so others can get on board and buy the book too. Writing blog posts can be hard enough, I couldn’t imagine writing a whole technical book so Jim deserves as much recognition and sales as possible.
Anyway, on to the good part, winner winner code for dinner and all that!
This chapter is all about diving deeper into our HelloCrossPlatformWorld app and enhancing it with MVVM features. Not just the concept of MVVM architecture but also the MVVMCross framework that I mentioned in the last post. You also get to do something fun by the end of the chapter, make your app speak to you! Section 1 begins with breaking down the app you created in Chapter 2 so that you can see where each layer of the MVVM pattern might fit. Being such a simple hello world app, you might think it doesn’t need MVVM but you would be surprised how it can still be split up and is a good starting point to iterate from in future. Section 1.2 covers the view model layer and specifically how this is implemented using MVVMCross. There are a few pieces of the puzzle you don’t need to worry about thanks to the framework because it implements some of the things you learned about earlier including INotifyPropertyChanged and PropertyChanged events. There is a useful mix of annotated screenshots and code samples to help you understand the mapping between what you now know and how it works in MVVMCross. Section 1.3 is the application layer. This is not technically one of the official layers in MVVM but it is still crucial to understand as it is where your app does various things including handling events such as what screen to load when the app starts, goes to sleep (either from screen lock or user pressing the home button normally) or resumes as the app has been brought back up. This can be quite powerful when used correctly but that is a topic for later. Next is the view section which is broken down into Android and iOS views, which are both implemented very differently. This is the first time you really get to learn and understand how the UI or “screens” are developed. On Android you have a version of XML called Android XML or AXML and on iOS the code to layout the UI is hidden behind a drag and drop style Storyboard page. Don’t worry if this sounds a bit confusing, the book does a great job of showing and explaining so when you come to make changes, you will feel in control. Again Jim uses annotated screenshots and references to the code you will have in your own project to refer to. Chapter 4 Section 2 is the fun bit, code time! As usual I will post a video of the app when you are done for this chapter. For the first time in this book, I found a diagram I would say was a little confusing. It may just be me but there is a diagram (Figure 4.9) showing how the ‘bait and switch’ technique works with cross-platform code but platform specific implementations at run time. It doesn’t follow the usual left to right top to bottom pattern and found myself looking for step 3 which turns out to be on the right. If I could offer any advice it would be swap the Android and .Net Standard boxes around or find a slightly different way to make the point. The book talks you through changing your app to add additional functionality and introduces some new concepts along the way such as Inversion of Control. I still find the name weird but Jim yet again finds a way to explain it in a way that at least makes me see WHY it is called that. I can see why he is paid by Microsoft to teach people things, he has a talent for it! Subsection 6, wiring up the iOS UI is where I hit my first real stumbling block. It wasn’t hard to resolve but Jim mentions clicking the highlighted button again once added to the storyboard to bring up the constraint bars, however this was not working on my version of Visual Studio for Mac and instead I just had to click the button in the top right as shown below:
Another thing to bear in mind if following along with the book is to not just follow the Steps 1, 2 and 3 for the required constraints but also look at the screenshot steps afterwards as it makes it much easier to follow along. Even after reading 3 times I am not convinced step 2 in the text is quite right but the screenshot is which makes it a lot easier. I have mentioned this to Jim so be aware this is only an issue at time of writing, it may be resolved by the time you try it out.
Once all that is setup, you can run the app and hey presto, it will speak to you!
<iframe width="680" height="382" src="https://www.youtube.com/embed/LBD3vB6W7Xc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
This is another chapter with some code you can try but mostly explanations. Mulithreading is a vital concept for mobile app development. If you don’t know what it is or don’t use it, NEVER and I mean NEVER upload to the app/play store! Have you ever been on an app that appears to freeze when you use it? Or takes so long that Android pops up and asks if you want to wait or close the app? This is often caused by an abuse or misunderstanding of threads and will cause a lot of users to complain.
Threads are your coffee making barista’s from the earlier coffee shop examples. If you only have 1 person being able to do 1 thing then you will be there a while since it can’t take the next order or whatever until it has done the one task it already has like making your coffee, or the coffee for the person in front of you. I highly recommend you take the time to sit through this and make sure you understand it all. Section 3 goes into further detail on the two main types of thread, the UI Thread (or main thread as you might have heard it called), and the background thread.
In my current role, I work using Amazon Web Services a lot and something called Simple Queue Service or SQS for lining up messages to process. Now you might be wondering why I told you this, you might not care what I do in my day job but in the section on UI threads, Jim discusses how the OS or your code sends ‘messages’ to the UI for tasks to carry out and it reminded me of that. Being able to relate to things helps you learn so I enjoyed that little lightbulb moment. Don’t get me wrong, SQS and UI Threads are not the same thing, I just found myself being able to have a faster understanding of threads because I had a personal experience to relate to.
Section 4 then moves on to how to make the most of the .Net threading system and tasks to run code in the background. The barista and coffee example continues to explain the impact of these concepts and a real world equivalent to help you understand.
You also get the chance to introduce some tasks into your HelloCrossPlatformWorld app where you can see the impact of using one thread to carry out multiple tasks, in this case imitating the delay you might experience if your main thread is calling out to a web service. The code samples are so short I won’t make a recording for each of these as no extra functionality is added except for an additional wait before it carries out the normal stuff.
Subsection 2 covers chaining tasks. This is important to know as you don’t always want things to happen in parallel. What if you have something that doesn’t need to happen on the main thread and lock up the UI but also another task that you don’t want to happen until the other has finished?
One of the examples Jim gives is an email app. You want the app to check for new email messages in the background but you don’t want it to download the content of the emails until that is done otherwise how will it know what to download? Plus checking for new email shouldn’t stop the user being able to read emails they have previously received and cached in the app. So learning how to chain tasks together is important. Thankfully .Net is kind enough to give you a method on a Task called ContinueWith.
Section 5 moves on to a topic I found myself wondering about earlier in the chapter, task results. Sometimes a task will not return anything, for example if you were the server in the coffee shop and asked the barista to make a coffee, you would expect to receive a cup of coffee as a result but if you were asking the employee in the kitchen to clean the floor, you are not expecting anything to come back just that a task is done.
There is more than one way to see if a task has finished. One way, as mentioned in subsection 1 is to poll the task and check if the inbuilt IsCompleted property is true. This is rarely used and quite wasteful as it requires code to run.
Subsection 2 covers waiting. There is a method on Task called Wait that means you block until the task has finished and that is how you know it is complete. Never do this on the UI thread or you are defeating the point of using tasks/threads.
Subsection 3 moves on to the recommended method which is using a continuation. We saw this earlier with the ContinueWith function.
Subsection 4 covers task exceptions. Up until this point we always assumed a job would go well and follow the “happy path”. But life doesn’t always work that way. The coffee machine might break or the barista might accidentally drop the cup before you get chance to drink your precious coffee :O!
Section 6 covers updating the UI. The book has already covered how you want to make use of background threads and not do everything on the UI thread but you still need a way of updating the UI when something is done. What use is an email app that downloads new emails if it never shows them to the user?!
This section has you covered in solving that issue and begins to explain more thread related concepts such as synchronization context and how you can actually get your UI to schedule a background task that then returns to the UI thread so it can update. Exactly what we want! It also explains how MVVM fits into this since we have already learned that you should use view models instead of views to do the UI logic. Now for the cause of the great chapter title. Section 7 is the magical async/await concept. If you have done C# development before you may have seen these as it is a core part of using threads and carrying out work asynchronously (not sequential basically). The idea is that you can call await on an async method so it waits for it to finish before continuing. There is quite a lot to all this so the section is quite long and full of tidbits.
Throughout this section again you will find regular little changes you can make to your example app to see the effect of async/await, like in earlier in the chapter. This idea of fiddling with the code and seeing the impact is the core of learning as a developer. “Make it, break it, fix it, learn” I have written on a post-it that lives on my laptop at work. Try not to break stuff here but the concept is still the same.
There is quite a few psuedocode style examples dotted around, showing you how you can take code that uses lots of task ContinueWith’s and use async and await to make it much more readable and clean. Uncle Bob would be proud! For those that don’t get that reference, Robert Martin or Uncle Bob as he is known is an advocate of clean code and even released a book on it.
Section 8 moves on to making your UI responsive. After all, it is one thing not freezing the app but if the app is not reacting as expected users will still keep trying to click that button over and over or whatever gesture is required. It is important to give some feedback that something is happening such as a loading symbol.
Couple more summary subsections then that’s it for Chapter 5 and more importantly, Xamarin in Action Part 1! Now the groundwork is set with some concepts and examples it is time to move on to Part 2 (in the next post of course) and start building some real app examples from start to finish.