How to use MVVM pattern in Android
This is a modal window.
Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.
Formale Metadaten
Titel |
| |
Serientitel | ||
Anzahl der Teile | 46 | |
Autor | ||
Lizenz | CC-Namensnennung 3.0 Unported: Sie dürfen das Werk bzw. den Inhalt zu jedem legalen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen. | |
Identifikatoren | 10.5446/47186 (DOI) | |
Herausgeber | ||
Erscheinungsjahr | ||
Sprache |
Inhaltliche Metadaten
Fachgebiet | ||
Genre | ||
Abstract |
|
droidcon Berlin 201514 / 46
5
7
10
13
16
18
20
21
23
26
31
34
35
36
41
42
45
00:00
MusterspracheHumanoider RoboterOffice-PaketWeg <Topologie>MusterspracheSoftwareentwicklerHumanoider RoboterImplementierungMehrrechnersystemFokalpunktSpielkonsoleProgram SlicingQuick-SortMereologieProzess <Informatik>Vorlesung/KonferenzBesprechung/Interview
00:52
SichtenkonzeptMultiplikationsoperatorProgram SlicingCodeGeradeVorlesung/Konferenz
01:21
Interface <Schaltung>DatenmodellSichtenkonzeptEreignishorizontDokumentenserverDateiformatClique <Graphentheorie>GeradeCodeEinfach zusammenhängender RaumSichtenkonzeptEreignishorizontCoxeter-GruppeMathematische LogikPhasenumwandlungInterface <Schaltung>Zusammenhängender GraphBitTopologieRechter WinkelSuite <Programmpaket>Dreiecksfreier GraphHumanoider RoboterEndliche ModelltheorieReelle ZahlZeichnungVorlesung/KonferenzBesprechung/InterviewComputeranimation
03:15
SichtenkonzeptInterface <Schaltung>OvalImplementierungOperations ResearchBitfehlerhäufigkeitRechenwerkSichtenkonzeptInterface <Schaltung>Mathematische LogikSoftwaretestHumanoider RoboterRechenwerkKomponententestCoxeter-GruppeFunktionalCodeArithmetische FolgePhysikalischer EffektImplementierungInhalt <Mathematik>
04:26
SichtenkonzeptDatenmodellGoogolCoxeter-GruppeBenutzerbeteiligungSoftwareentwicklerHumanoider RoboterApp <Programm>BildschirmfensterKartesische KoordinatenCoxeter-GruppeWeb-DesignerInformationsspeicherungJSONComputeranimation
05:31
QuaderSichtenkonzeptEndliche ModelltheorieCoxeter-GruppeÄhnlichkeitsgeometrie
05:57
DatenmodellEreignishorizontKategorie <Mathematik>SichtenkonzeptEndliche ModelltheorieDifferenteSchnelltasteCoxeter-GruppeEreignishorizontBitMinimumElektronisches ForumQuick-Sort
07:11
DatenmodellEreignishorizontKategorie <Mathematik>Wiederkehrender ZustandProgrammbibliothekSystemaufrufGeradeCodeApp <Programm>MusterspracheImplementierungSystemplattformMereologieRechter WinkelJSONXMLUMLVorlesung/KonferenzBesprechung/Interview
07:45
SichtenkonzeptOvalFaserbündelCodeVersionsverwaltungHumanoider RoboterVererbungshierarchieStellenringKategorie <Mathematik>SichtenkonzeptSchnelltasteEndliche ModelltheorieElektronische PublikationMailing-ListeParametersystemFunktionalEreignishorizontAppletNormalvektorKlasse <Mathematik>EindringerkennungSoftwareentwicklerDifferenteTypentheorieDesign by ContractLie-GruppeGraphfärbungSpielkonsoleWeb SiteMinimumMultiplikationsoperatorNotebook-ComputerHumanoider Roboter
10:20
Wiederkehrender ZustandProgrammbibliothekSchnelltasteÄhnlichkeitsgeometrieMailing-ListeGoogolApp <Programm>SoftwareentwicklerOrdnung <Mathematik>AdditionBildschirmfensterProgrammbibliothekCodeSichtenkonzeptVersionsverwaltungUmsetzung <Informatik>MultiplikationsoperatorAppletMathematische LogikHumanoider RoboterSchnelltasteCoxeter-GruppeDifferenteApp <Programm>TypentheorieFramework <Informatik>QuellcodeEndliche ModelltheorieBildschirmmaskeRechter WinkelSystemplattform
12:38
SchnelltasteHumanoider RoboterÜbersetzer <Informatik>BimodulGruppenkeimFramework <Informatik>Humanoider RoboterPlug inCMM <Software Engineering>SchnelltasteVorlesung/Konferenz
13:05
OvalZeichenketteDatenmodellHumanoider RoboterVererbungshierarchieSichtenkonzeptComputervirusKlasse <Mathematik>SchnelltasteCoxeter-GruppeSichtenkonzeptEreignishorizontServerKategorie <Mathematik>DatenfeldAttributierte Grammatikp-BlockObjekt <Kategorie>Endliche ModelltheorieClique <Graphentheorie>KreisflächeOrdnung <Mathematik>Einfach zusammenhängender RaumInstantiierungMathematikCode
15:22
CodegenerierungProgrammbibliothekMailing-ListeTypentheorieZirkel <Instrument>Kartesische KoordinatenRechter WinkelProdukt <Mathematik>Umsetzung <Informatik>Projektive EbeneNeuroinformatikSoundverarbeitungSchnelltasteSpieltheorieTypentheorieInformationsspeicherungCodeProgrammbibliothekMailing-Liste
16:20
TopologieCoxeter-GruppeProjektive EbeneGebäude <Mathematik>ImplementierungStichprobenumfangFramework <Informatik>VerschlingungSchreiben <Datenverarbeitung>App <Programm>BenutzerbeteiligungVorlesung/Konferenz
16:53
Humanoider RoboterDatenmodellKlasse <Mathematik>Mailing-ListeProgrammbibliothekSchnelltasteCodegenerierungSichtenkonzeptSchnelltasteMailing-ListeSchnittmengeGenerator <Informatik>Endliche ModelltheorieFunktionalProgrammbibliothekAttributierte GrammatikKategorie <Mathematik>StichprobenumfangCodeDatenfeldProdukt <Mathematik>Klasse <Mathematik>EnergiedichteProzess <Informatik>BitrateBildschirmmaskeMathematikRechter WinkelEinsLeistung <Physik>Computeranimation
18:30
Humanoider RoboterKlasse <Mathematik>ZeichenketteOvalVererbungshierarchieDatenmodellATMSchnelltasteCodegenerierungProgrammbibliothekAnalog-Digital-UmsetzerNormalvektorEinsAttributierte GrammatikCodeKategorie <Mathematik>CASE <Informatik>SchnelltasteSichtenkonzeptElektronische PublikationHumanoider RoboterMultiplikationsoperatorMathematikUmsetzung <Informatik>ZeichenketteProgrammbibliothekSchreiben <Datenverarbeitung>EreignishorizontCompilerSummierbarkeitEndliche ModelltheorieGenerator <Informatik>QuaderZirkel <Instrument>Klasse <Mathematik>Prozess <Informatik>GraphfärbungDatenfeldProgramm/QuellcodeJSON
20:24
ProgrammbibliothekSchnelltasteHumanoider RoboterHill-DifferentialgleichungGoogolEndliche ModelltheorieInformationAttributierte GrammatikLie-GruppeVariableFamilie <Mathematik>SchnelltasteElektronische PublikationWeb SiteWellenpaketSichtenkonzeptGebäude <Mathematik>CASE <Informatik>App <Programm>RoutingKategorie <Mathematik>ProgrammbibliothekPlug inHumanoider RoboterOrdnung <Mathematik>
22:22
SchnelltasteHumanoider RoboterProgrammbibliothekZeichenketteOvalVererbungshierarchieSchnelltasteSichtenkonzeptElektronische PublikationInhalt <Mathematik>StichprobenumfangEndliche ModelltheorieProgrammbibliothekLuenberger-BeobachterMereologieProzess <Informatik>Klasse <Mathematik>Demo <Programm>RechenschieberOrdnung <Mathematik>Humanoider RoboterCodeArithmetischer AusdruckFormale SpracheGoogolCASE <Informatik>EreignisdatenanalyseGenerator <Informatik>ServerReelle ZahlVariableSystemaufruf
24:36
Humanoider RoboterProgrammbibliothekSchnelltasteSchnelltasteZeichenketteFormale SpracheDateiformatArithmetischer AusdruckParametersystemDatenfeldDifferenteSichtenkonzeptTypentheorieHydrostatikKlasse <Mathematik>Endliche ModelltheorieComputerspielFunktionalDatensatzProjektive EbeneWeb SiteMehrrechnersystemCASE <Informatik>Automatische HandlungsplanungFlächentheorieNatürliche SpracheProzess <Informatik>StichprobenumfangVorlesung/Konferenz
26:47
Humanoider RoboterSchnelltasteProgrammbibliothekGoogolCodegenerierungProgrammierumgebungFehlermeldungCodeFormale SpracheRegulärer Ausdruck <Textverarbeitung>StandardabweichungÜbersetzer <Informatik>MusterspracheSoftwaretestRechenwerkEndliche ModelltheorieSchreiben <Datenverarbeitung>SichtenkonzeptSchnelltasteEndliche ModelltheorieFormale SpracheArithmetischer AusdruckProgrammbibliothekComputerspielMusterspracheSampler <Musikinstrument>Humanoider RoboterStandardabweichungSoftwareentwicklerProgrammierumgebungCodeFehlermeldungRechter WinkelGoogolMultiplikationsoperatorFunktionalOrtsoperatorGenerator <Informatik>Prozess <Informatik>Mehrschichten-PerzeptronTotal <Mathematik>Familie <Mathematik>GefangenendilemmaCoxeter-GruppeComputeranimation
28:29
Konvexe HülleHumanoider RoboterSchreiben <Datenverarbeitung>KomponententestVerschlingungSichtenkonzeptCoxeter-GruppeComputeranimation
Transkript: Englisch(automatisch erzeugt)
00:05
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.
00:26
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.
00:44
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?
01:06
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,
01:22
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.
01:44
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.
02:01
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.
02:21
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.
02:45
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.
03:03
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.
03:22
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
03:40
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,
04:02
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.
04:24
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?
04:43
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.
05:03
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
05:22
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.
05:45
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,
06:03
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.
06:20
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,
06:41
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,
07:05
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,
07:22
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.
07:45
So, maybe one joke. Do you know why Java developers are wearing glasses? Because they don't C-Sharp.
08:02
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
08:24
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,
08:45
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.
09:02
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.
09:26
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
09:47
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,
10:02
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.
10:22
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.
10:42
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.
11:03
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.
11:24
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?
11:41
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.
12:05
Because the tint which is done by AppCompat library may not work. But as far as I know, there is one gist on GitHub.
12:21
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.
12:45
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.
13:06
Okay. So, our presentation, our ViewModel, which here is called... which is annotated with presentation model. But it's ViewModel for us.
13:21
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.
13:43
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,
14:02
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.
14:21
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
14:44
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.
15:03
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.
15:24
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
15:44
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.
16:04
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.
16:22
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,
16:43
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,
17:01
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.
17:20
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,
17:42
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.
18:03
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.
18:22
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.
18:43
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.
19:05
But when we look at our activity, unfortunately, we are forced to use FindView by ID or butter knife because, as I said,
19:21
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
19:41
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,
20:01
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.
20:20
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.
20:42
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
21:02
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.
21:21
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
21:42
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.
22:02
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
22:22
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.
22:42
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,
23:03
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
23:22
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.
23:41
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,
24:05
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.
24:28
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.
24:44
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.
25:02
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
25:21
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
25:41
to create custom binding for site review. And, okay, sorry about that.
26:02
And here you can see... I don't know why it's not playing. Okay. A really simple example with RecyclerView.
26:22
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,
26:42
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.
27:01
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.
27:22
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
27:40
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,
28:05
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.
28:23
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.
28:43
And here are all the links for these libraries, demos, etc. Any questions?