We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

How to use MVVM pattern in Android

00:00

Formal Metadata

Title
How to use MVVM pattern in Android
Title of Series
Number of Parts
46
Author
License
CC Attribution 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor.
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
I would like to show how to use Model-View-ViewModel (MVVM) design pattern on the Android platform. Using this aproach UI code is easier to read, test and maintain. I will show how it can help to: remove lots of unnecessary code not write boilerplate code any more turn Android unit tests running for ages into pure POJO PresentationModels with normal JUnit tests I will present framework which helps to achieve this goals and how to configure gradle build script to use it.
Pattern languageAndroid (robot)Office suiteTrailPattern languageSoftware developerAndroid (robot)ImplementationComputer clusterFocus (optics)Video game consoleProgram slicingQuicksortMereologyProcess (computing)Lecture/ConferenceMeeting/Interview
View (database)Multiplication signProgram slicingCodeLine (geometry)Lecture/Conference
Interface (computing)Data modelView (database)Event horizonRepository (publishing)File formatClique problemLine (geometry)CodeConnected spaceView (database)Event horizonPresentation of a groupLogicPhase transitionInterface (computing)Connectivity (graph theory)BitNetwork topologyRight angleSuite (music)Cycle (graph theory)Android (robot)Endliche ModelltheorieReal numberDrawingLecture/ConferenceMeeting/InterviewComputer animation
View (database)Interface (computing)OvalImplementationOperations researchBit error rateExecution unitView (database)Interface (computing)LogicSoftware testingAndroid (robot)Execution unitUnit testingPresentation of a groupFunctional (mathematics)CodeArithmetic progressionCausalityImplementationContent (media)
View (database)Data modelGoogolPresentation of a groupWeb 2.0Software developerAndroid (robot)Mobile appWindowCartesian coordinate systemPresentation of a groupWeb-DesignerData storage deviceJSONComputer animation
CuboidView (database)Endliche ModelltheoriePresentation of a groupSimilarity (geometry)
Data modelEvent horizonCategory of beingView (database)Endliche ModelltheorieDifferent (Kate Ryan album)Keyboard shortcutPresentation of a groupEvent horizonBitGreatest elementInternet forumQuicksort
Data modelEvent horizonCategory of beingRepetitionLibrary (computing)System callLine (geometry)CodeMobile appPattern languageImplementationComputing platformMereologyRight angleJSONXMLUMLLecture/ConferenceMeeting/Interview
View (database)OvalFiber bundleCodeRevision controlAndroid (robot)Inheritance (object-oriented programming)Local ringCategory of beingView (database)Keyboard shortcutEndliche ModelltheorieComputer fileElectronic mailing listParameter (computer programming)Functional (mathematics)Event horizonJava appletNormal (geometry)Social classIntrusion detection systemSoftware developerDifferent (Kate Ryan album)Type theoryDesign by contractLie groupGraph coloringVideo game consoleWebsiteGreatest elementMultiplication signLaptopAndroid (robot)
RepetitionLibrary (computing)Keyboard shortcutSimilarity (geometry)Electronic mailing listGoogolMobile appSoftware developerOrder (biology)AdditionWindowLibrary (computing)CodeView (database)Revision controlData conversionMultiplication signJava appletLogicAndroid (robot)Keyboard shortcutPresentation of a groupDifferent (Kate Ryan album)Mobile appType theorySoftware frameworkSource codeEndliche ModelltheorieForm (programming)Right angleComputing platform
Keyboard shortcutAndroid (robot)CompilerModule (mathematics)Local GroupSoftware frameworkAndroid (robot)Plug-in (computing)Capability Maturity ModelKeyboard shortcutLecture/Conference
OvalString (computer science)Data modelAndroid (robot)Inheritance (object-oriented programming)View (database)Computer virusSocial classKeyboard shortcutPresentation of a groupView (database)Event horizonServer (computing)Category of beingField (computer science)Attribute grammarBlock (periodic table)Object (grammar)Endliche ModelltheorieClique problemCircleOrder (biology)Connected spaceInstance (computer science)MathematicsCode
Code generationLibrary (computing)Electronic mailing listType theoryCompass (drafting)Cartesian coordinate systemRight angleProduct (business)Data conversionProjective planeNeuroinformatikSound effectKeyboard shortcutGame theoryType theoryData storage deviceCodeLibrary (computing)Electronic mailing list
Network topologyPresentation of a groupProjective planeBuildingImplementationSampling (statistics)Software frameworkLink (knot theory)WritingMobile appWeb 2.0Lecture/Conference
Android (robot)Data modelSocial classElectronic mailing listLibrary (computing)Keyboard shortcutCode generationView (database)Keyboard shortcutElectronic mailing listSet (mathematics)Electric generatorEndliche ModelltheorieFunctional (mathematics)Library (computing)Attribute grammarCategory of beingSampling (statistics)CodeField (computer science)Product (business)Social classFood energyProcess (computing)Bit rateForm (programming)MathematicsRight angle1 (number)Power (physics)Computer animation
Android (robot)Social classString (computer science)OvalInheritance (object-oriented programming)Data modelAsynchronous Transfer ModeKeyboard shortcutCode generationLibrary (computing)Analog-to-digital converterNormal (geometry)1 (number)Attribute grammarCodeCategory of beingCASE <Informatik>Keyboard shortcutView (database)Computer fileAndroid (robot)Multiplication signMathematicsData conversionString (computer science)Library (computing)WritingEvent horizonCompilerSummierbarkeitEndliche ModelltheorieElectric generatorCuboidCompass (drafting)Social classProcess (computing)Graph coloringField (computer science)Source codeJSON
Library (computing)Keyboard shortcutAndroid (robot)Hill differential equationGoogolEndliche ModelltheorieInformationAttribute grammarLie groupVariable (mathematics)FamilyKeyboard shortcutComputer fileWebsiteWave packetView (database)BuildingCASE <Informatik>Mobile appRoutingCategory of beingLibrary (computing)Plug-in (computing)Android (robot)Order (biology)
Keyboard shortcutAndroid (robot)Library (computing)String (computer science)OvalInheritance (object-oriented programming)Keyboard shortcutView (database)Computer fileContent (media)Sampling (statistics)Endliche ModelltheorieLibrary (computing)State observerMereologyProcess (computing)Social classDemo (music)Slide ruleOrder (biology)Android (robot)CodeExpressionFormal languageGoogolCASE <Informatik>Survival analysisElectric generatorServer (computing)Real numberVariable (mathematics)System call
Android (robot)Library (computing)Keyboard shortcutKeyboard shortcutString (computer science)Formal languageFile formatExpressionParameter (computer programming)Field (computer science)Different (Kate Ryan album)View (database)Type theoryFluid staticsSocial classEndliche ModelltheorieVideo gameFunctional (mathematics)Row (database)Projective planeWebsiteComputer clusterCASE <Informatik>PlanningSurfaceNatural languageProcess (computing)Sampling (statistics)Lecture/Conference
Android (robot)Keyboard shortcutLibrary (computing)GoogolCode generationIntegrated development environmentError messageCodeFormal languageRegulärer Ausdruck <Textverarbeitung>Standard deviationCompilerPattern languageSoftware testingExecution unitEndliche ModelltheorieWritingView (database)Keyboard shortcutEndliche ModelltheorieFormal languageExpressionLibrary (computing)Video gamePattern languageCompilation albumAndroid (robot)Standard deviationSoftware developerIntegrated development environmentCodeError messageRight angleGoogolMultiplication signFunctional (mathematics)Position operatorElectric generatorProcess (computing)Labour Party (Malta)Total S.A.FamilyPrisoner's dilemmaPresentation of a groupComputer animation
Convex hullAndroid (robot)WritingUnit testingLink (knot theory)View (database)Presentation of a groupComputer animation
Transcript: English(auto-generated)
Welcome, everyone. My name is Radek Pekas. I work for Making Waste Polska. We have offices in Oslo, Stockholm, and Krakow, of course. And I'm really excited to be here. And I would like to talk today with you about MVVM pattern on Android.
First, I will show that Android developers need better tools for development. And how can we make things better? And before, I will talk about MVVM pattern. I will just, in a few slides, I will talk about MVP.
And later, I will focus on MVV implementations on Android, which are available right now. I will discuss pros and cons for each of them. And then I will summarize everything. So how many times have you written these lines of code?
And one? Yeah. I think that we are wasting too much time writing these lines of code. And we are doing this every time, day by day. And I'm pretty sure that's not only me,
that is reacting like this when I saw these lines of code. And hopefully, the Android community is helping us to solve this problem. We can use, for example, butter knife to remove this fine view by ID stuff and have better on-click connection.
But for example, we have Android annotations too. However, the real question is, is it enough? So who thinks that these solutions are enough for us? Please raise your hand.
OK. So we are on the right talk today. Because the correct answer is no. It's not enough. So first, I will talk a little bit about Model View Presenter. And in Model View Presenter, we can distinguish three components. Model, Presenter, and View.
The Model is the interface which is defining the data to be displayed. The View is only the passive View, so it shouldn't have any logic. It should only send events to Presenter or display the data. And the logic for displaying this View should be in the Presenter.
So when user will show this. So when we have our passive View, when user clicks, we send this event to Presenter. And Presenter will do something with this event. And for example, updates the Model.
However, when the Model will raise the state change event, Presenter will know about this and will update the View. So this is quite an easy example. And we can check how we can implement this on Android. So let's define simple interface for our View.
We can create three methods, height loading, show loading, and render items. Our View Presenter in initialize method will just execute these methods on the View. And our activity or fragment can just
implement this interface for View. And here we can just show or hide, for example, progress bar. And I think it's not bad because we have separated the logic from the View. And we can easily create unit tests for our Presenter,
which is much better than creating functional testing or UI testing because running normal unit tests using JUnit is much, much faster than normal functional testing on Android because we don't need to run any code on emulator, on Genymotion, et cetera. However, we can do this better.
And this is when MVVM comes in. So say hello to Model, ViewViewModel. And the question is, does anyone know this pattern? Are you Microsoft developers or?
OK, maybe someone from the web. OK, so an Android JS or a Knockout. OK, so currently MVVM is really popular across C Sharp community, especially when you are creating desktop apps or Windows phone apps.
And through the web developers, maybe you heard about Android JS or Knockout. They are quite popular right now, especially Angular, which is promoted by Google. On Microsoft it was used in Microsoft Silverlight
and on desktop application in Windows Presentation Foundation. So let's start to explain what is this Model, ViewViewModel. It's similar to MVP because we have three parts, View, ViewModel, and Model.
Model is only the data which is independent from the view. So we can use many views to display the same data. And ViewModel is quite similar to presenter from the Model View Presenter pattern,
but it works a little bit different. For example, when user will click on button on our view, the button will rise event, UI event, and will inform the ViewModel that something was changed or the user clicked.
And ViewModel will do something with this data, and for example, update the model. However, when something will change in the model, the model will raise the event that something was changed. ViewModel will get this event, maybe read the data from Model, because ViewModel has this data inside it,
and then rise the event prepared to change, which is really important because this is the clue with this ViewModel. And when View will get this prepared to change event, it will, for example, get this data from ViewModel and display it on the view,
which is quite similar to, as I said, to Model View Presenter. However, all of this magic here between View and ViewModel is done by using binding. So, you don't have to write any line of code to update the UI,
which is really great. And now I will present first of the libraries you can use. It's MVVM-Cross, and it's a great example of MVVM pattern implementation on the right. However, it was created for Xamarin, so you can use it only when you are creating your app using C-Sharp and Xamarin platform.
So, maybe one joke. Do you know why Java developers are wearing glasses? Because they don't C-Sharp.
Okay, so this is a really simple example of activity, which was right throughout using C-Sharp. And the most important thing is the white... Okay, maybe you don't see everything. The most important thing is that we are extending MVX activity
and we are specifying our ViewModel, and that's it. We don't have to write anything more in our activity. So, let's look at our XML file with the layout. It looks like a mostly normal layout for Android,
besides two small differences. We are using a list control, which comes with MVVM-Cross. We have some custom attributes when we are specifying our binding.
And, as you can see, it's not hard and maybe we'll go to our ViewModel. And we are extending MVVM-Cross, which is, again, a class from MVVM-Cross. And we are simply defining some properties which will return data to the model.
If you want to, for example, connect a button to our method in our ViewModel, we need to just create a property of type iMvxCommand. And the parameter of this mvxCommand is a function or method
which should be run during this command. But maybe some of you already see this, but when we set the value on our property items,
we are raising RaisePropertyChangeEvent. And this event will inform the MVVM-Cross that something was changed in our ViewModel, and MVVM-Cross will automatically update our view. So, as you can see, we don't have this fine view via IDs.
We don't have to write any adapters. It's great because it saves us a lot of time. But maybe what are the pros and cons of this solution? So, first of all, we have two-way binding. So, when user will update the data in our view, we will get notified and we will get this data.
Or we can update the view from our code. It's easy to extend because we can write our custom bindings. We can create custom converters for many different types, which is really great. We can reuse this ViewModel across iOS, Windows Phone, and Android.
So, we can write only once the logic in the ViewModel and use it across different platforms, which is really great. And just create native views for Android, iOS, et cetera. And it is used by many developers. And many apps were published using this framework.
So, I think that it's ready to use. And it's really through MVVM, and it's quite similar to Windows Presentation Foundation. And if someone was programming using C-Sharp probably knows it. And what are the cons?
First of all, it's only for C-Sharp and Xamarin. And may need some additional work in order to make it work with AppCompat library. Because some of the libraries which are created for MVVM on Android can cause some problems when on the older devices, which are older devices which are not with lollipop version.
Because the tint which is done by AppCompat library may not work. But as far as I know, there is one gist on GitHub.
How to make MVVM cross-work with AppCompat on previous versions of Android. Okay. So, now we are switching to Java again. And now I will talk about RoboBinding. Anyone heard about it? Okay. So, I think that this is probably the most mature MVVM framework for Android.
It's written in Java. And it can be easily used by Gradle, using Gradle. So, when we want to use it, we need to add Android APT plugin to our Gradle. And then just add some dependencies for RoboBinding.
Okay. So, our presentation, our ViewModel, which here is called... which is annotated with presentation model. But it's ViewModel for us.
And need to implement hasPresentationModelChangeSupport if we want to... if you want to be... if you want to make sure that our code will be ready to send notification to the View that some of our properties were changed.
So, what is really important here? We need to create presentation model change support class. And overwrite getPresentationModelSupport method in order to return this object. And then if we change value in our ViewModel or in our View,
we need to execute the method firePropertyChange with the name of the property which was changed. And if we will do everything correctly, our View should be updated. And if we are talking about View, let's switch to our activity.
So, here again, now findViewByIds. And only thing that we need to do is to create main View, our instance of our ViewModel and connect it to the View. And in order to do this, we need to use a class which comes with RoboBinding
and execute method inflate and bind without blah, blah, blah. So, again, it's really easy. So, what about our XML? And the most important things are, again, custom attributes.
And if you want to have two-way binding, we need to add $. You can see this in the third white text. And we can easily connect events, for example, onClick. And that's all for the RoboBinding.
Prose, it has working two-way binding. It's generating code during compilation, so there should not be problems with performance. It's easy to extend because, again, we can create our custom bindings, custom converters, so we can write once
and use many of our custom bindings across the projects. And it's a poor list, so it's really important for us. However, currently, it's not supporting RecitalView. It has problems with AppCompat library.
And it's not supporting lists with two and more types of item layout. So, I'm not sure if anyone is using it in the production application on Google Play Store. However, it's nice to know about it.
I prepared a short demo, and if you want to check how you can write simple app with RoboBinding, you can check here. The links will be at the end of the presentation, too. And now, another approach, ng-android. This is the next example of MVVM implementation Android,
and it was inspired by AngularJS, which is a MVVM framework for web and JavaScript. And what we have to do to implement ng-android in our project, this is a sample fragment,
and what is important is that we need to start by annotating our view with ng-scope. We need to create fields with our view model and annotate it with ng-model, and my view model is called here ng-mode.
And then we need to inflate our view using ng-android class, which is, again, which comes with ng-android. And this is all in our view. Our view model is quite simple. It just gets our set string,
and our layout, again, it may look similar to RoboBinding. We need to add some custom attributes and just say which property should be used on, for example, text view or edit text.
Pros. It has two-way binding. Again, there is code generation. However, there is no support for lists or less likely view, and it's not production-ready library. Currently, there is some functionalities missing there, but, again, it's really nice to know this.
Maybe in the future it will be more helpful for us. And just honorable mention for BankDroid. It's another MVVM approach. It's quite different from previous ones because you don't create any custom attributes and make changes in your XML files.
Everything you have to do is just create ViewModel again. With BankDroid, we have TrackableField class, which is responsible for all of these events between View and ViewModel. So the important stuff is here.
But when we look at our activity, unfortunately, we are forced to use FindView by ID or butter knife because, as I said,
BankDroid does not have support for custom attributes in our XML file. So we need to write everything by ourselves. And I think it's horrible. But maybe in some cases it might be helpful for you. Pros. It has two-way binding. It works with AppCompat library
because we are inflating our View using normal Android methods. It has converter support and the cons. There is no code generation, unfortunately. There is no compile time checking if everything is okay. So when we will change,
for example, the name of the property, it will fail because we pass the name of the property as a string in our code. So this is a really big problem, I think. And we need to write too much code for bindings.
And I think that many of you are waiting for this. So do you know what I will talk about now or not? Okay, so during Google I.O., Google announced their own data binding library.
And now I will be talking about this. So it was announced by Google during Google I.O. this year. It's created by Google, of course. And currently it's available as beta. And if you want to use it, we need to
add a plugin to our Gradle, which is DataBinder. And Apply is plugging in our app Gradle build file. And what is really important for us is that now the layout of the XML file will change.
In our route we will have a layout node. Then we have a data node with variables. I will talk about it later. And in our data, we can specify
information about variables that will be used in our views. So in our case, it will be, of course, our view models. However, we can pass other variables from our view or our activity to the binding library.
And last but not least, of course, we have custom attributes in order to make the binding for our view model properties. I don't want to be boring, so I will not be talking about
Android data binding library itself because you can read the documentation about it. So I prepared an example how to use it. And with RecyclerView, because I think it's more interesting than simple hello world stuff. And I can say that it's doable.
I spent maybe two hours to learn the data binding library and connect it to the RecyclerView. So first what we need is we need to create our base view model. And Google comes with observable array list,
which is responsible for notifying our view that, for example, we add new item to the list, et cetera. And if you want to make this be enabled to the view, we need to annotate it with bindable annotation. And I have sample
at user method in order to add some new user. Okay. And what about our activity? The most important parts are here. So first we need to create our view model. Then we need to bind this view model to our view.
So we are using data binding set content view method, which is from data binding library. And then we can, we should, of course, set our view model to the view. And because data binding library is using code generation, it generates data binding class for each view,
which we are using with this library. And it expose the method to set the variables, which we defined in our XML file. So in my case, it was user view model, which is for my view model.
And that's it. I will show the demo in the next slide. And what is really great about this Android data binding library is that Google made a tremendous job to add some cool expression language to this binding.
So we can, for example, execute string format in XML with parameters from our view model. We can import some static methods from other classes and use them in our binding.
We can use resources in our bindings. And it has built-in button life functionality. So when we are using views which have IDs, the generating binding class will expose these fields
by using the ID. So it will generate the field using the name, the ID which we used in our XML. And of course, we can create our custom bindings. So in my case, I used functionality
to create custom binding for site review. And, okay, sorry about that.
And here you can see... I don't know why it's not playing. Okay. A really simple example with RecyclerView.
The first row is one type of the layout, and the rest of them are the second one. So as you can see, we can create binding for RecyclerView which will support many different types of items. And you can check on GitHub this example,
and I'm pretty sure that you can use this binding in your project because I was using generics, so you can connect it to any other model you want. So pros and cons. Pros, of course, is official library from Google.
Yeah, we like it. It uses code generation. Cool. It has compile time check, so when we will change something in our code and forget about changing something, for example, our view, it will inform us during compilation about our error. It's really easy to use and extend.
The really great feature is this expression language. And I think, maybe not now, but in the next few months, it will become the new standard in Android development. And the cons. Unfortunately, right now, there is no two-way binding. I asked one guy from Google
if they are preparing to add this functionality in the future, and he said that they have it on their to-do list, but he doesn't know when they will implement it. And unfortunately, currently, there is no IDE support for this library,
so you will have a lot of false positive errors in IDE. However, the code will compile and run. So, first takeaway from this presentation. Please learn and use MVP pattern.
It will make your life really easier. Second one. Get familiar with MVVM and try Android data binding library. And write unit tests for your presenters and view models. So, if you have any questions, just ask me.
And here are all the links for these libraries, demos, etc. Any questions?