SlideShare a Scribd company logo
1 of 31
Download to read offline
MVVM & Data Binding
Library
Wojciech Topolski
Agenda
• Theory of MVVM
• Data Binding Library
• Custom MVVM(C) implementation
• View Model Composition
• Binding & RecycleView
• Grabbing value directly from View
• Links
Theory of MVVM
• "MVVM facilitates a separation of development of the graphical user interface from development of the
business logic. The view model of MVVM is a value converter; meaning the view model is responsible for
exposing (converting) the data objects from the model in such a way that objects are easily managed and
presented. In this respect, the view model is more model than view, and handles most if not all of the
view's display logic. The view model may implement a mediator pattern, organizing access to the back-
end logic around the set of use cases supported by the view.” (Wikipedia)
• Model - Business data layer, it could be set of POJO objects or layer operating on database/network/
cache. Must be independent of user interface.
• View - User interface.
• View Model - It is responsible for converting data between Model and View, visibility of View components.
Data Binding Library
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

MainActivityBinding binding;

binding = DataBindingUtil.setContentView(this, R.layout.main_activity);

User user = new User("Test", "User");

binding.setUser(user);

}
<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data>

<variable name="user" type="com.example.User"/>

</data>

<LinearLayout ...>

<TextView

android:text="@{user.firstName}"/>

<TextView

android:text="@{user.lastName}"/>

</LinearLayout>

</layout>
BY EXAMPLE
Android Plugin for Gradle 2.1+

https://developer.android.com/topic/libraries/data-binding/index.html
Data Binding Library
Variables and imports in <data>...</data> section.

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:bind="http://schemas.android.com/apk/res-auto">

<data>

<import type="android.view.View" />

<variable

name="viewModel"

type="com.github.wtopolski.libmvvm.viewmodel.ButtonViewModel"/>

</data>



<Button . . . />



</layout>
FEATURE 1 / 15
Data Binding Library
Widgets are available by binding.id expression, where
id is equal to content of android:id attribute. However,
android:id is not obligatory at all.
<TextView android:id=“@+id/someTextView" />
ActivityMainBinding binding = DataBindingUtil.setContentView(

this, R.layout.activity_main);


binding.someTextView.setText("XYZ");
FEATURE 2 / 15
Data Binding Library
Setting almost every widget XML attribute is
possible. Directly by setter paired with attribute like
android:enabled and view.setEnabled(boolean). Or
indirectly using BindingAdapter or BindingMethods.
<EditText

android:enabled=“@{viewModel.enabled}" />
FEATURE 3 / 15
Data Binding Library
Observable variables. Every data change could be
reflected to View. "You can change your data model in
a background thread as long as it is not a collection."
public class BaseViewModel extends BaseObservable {

private boolean enabled;



public void setEnabled(boolean enabled) {

this.enabled = enabled;

notifyPropertyChanged(BR.enabled);

}



@Bindable

public boolean getEnabled() {

return enabled;

}

}
<EditText

android:enabled=“@{viewModel.enabled}" />
FEATURE 4 / 15
Data Binding Library
Two-way data binding allows synchronization
widget's state between user interface and passed
variable. Main restriction is XML attribute must
have listener indicating change of value.


<EditText

android:text="@={viewModel.value}" />
FEATURE 5 / 15
Data Binding Library
EventHandling::MethodReference
• "listener implementation is created when the data is bound”
• "expression is processed at compile time, so if the method does not exist or its signature is not
correct, you receive a compile time error.”
• "method must match the parameters of the event listener”
<Button

android:onClick="@{viewModel::onButtonClick}” />
public void onButtonClick(View view) {

// Some action

}
FEATURE 6 / 15
Data Binding Library
() -> EventHandling.ListenerBindings()
• "listener implementation is created when event is triggered”
• "return value must match the expected return value of the listener (unless it is
expecting void)”
<Button

android:onClick=“@{() -> viewModel.onButtonClick()}” />
public void onButtonClick() {

// Some action

}
FEATURE 7 / 15
Data Binding Library
BindingAdapter allows to set any data using custom
XML attribute. The same solution helps to write
attributes for custom widgets. No more attrs.xml
files!
@BindingAdapter({"errorEnabled"})

public static void errorEnabled(TextInputLayout view, String value) {

view.setError(value);

view.setErrorEnabled(!TextUtils.isEmpty(value));

}
<android.support.design.widget.TextInputLayout

bind:errorEnabled="@{viewModel.valueError}">
FEATURE 8 / 15
Data Binding Library
BindingMethods "Some attributes have setters that
don't match by name… For example, the
android:tint attribute is really associated with
setImageTintList(ColorStateList), not setTint."
@BindingMethods({

@BindingMethod(

type = "android.widget.ImageView",

attribute = "android:tint",

method = "setImageTintList")

})
FEATURE 9 / 15
Data Binding Library
Converter helps to translate given value format into
format which is expected by specific XML tag.
@BindingConversion

public static ColorDrawable convertColorToDrawable(String color) {

return new ColorDrawable(Color.parseColor(color));

}
<LinearLayout

android:background="@{viewModel.color}">
FEATURE 10 / 15
Data Binding Library
In custom XML attributes we can use application
resources.
<TextView

bind:textColor="@{@color/green}" />


<resources>

<color name="green">#009900</color>

</resources>
FEATURE 11 / 15
Data Binding Library
Null Coalescing Operator
<TextView

android:text=“@{user.displayName ?? user.lastName}” />
FEATURE 12 / 15
Data Binding Library
Including layouts. More in View Model Composition
section.
<include

layout="@layout/text_view"

android:layout_width=“match_parent"

android:layout_height=“wrap_content"

bind:viewModel="@{viewModel.redDesc}"

bind:textColor="@{@color/red}" />
FEATURE 13 / 15
Data Binding Library
Immediate Binding. "When a variable or observable
changes, the binding will be scheduled to change
before the next frame...To force execution, use the
executePendingBindings() method."
binding.executePendingBindings();
FEATURE 14 / 15
Data Binding Library
Data Binding doesn't use reflection. Binding classes
are generated almost in real time by Android Studio,
and they are part of application. You can find them in
build directory.
.../build/intermediates/classes/debug/package_name/databinding/*
FEATURE 15 / 15
Custom MVVM(C) implementation
• Bases on Data Binding Library and RxJava
• Layers:
• Model - business data layer (POJO, Database, Cache,
Backend)
• View - user interface (XML and Binding)
• View Model - conversion between displayed data and stored
data (model), validation of forms, etc…
• What’s about Activity and Fragment? Is it View or View Model?
• Or maybe MVVMC? Where:
• Controller - is responsible for global actions like open new
Activities
• View Model - takes care about operation on single screen
https://github.com/wtopolski/androidmvvm
View Model Composition
Real app screens are complicated. Usually they
contain several input and output widgets like
EditText, Button, SeekBar, RecycleView, etc.
It would be useful to create set of Views and View
Models. And then reuse them to composite user
interface.
View Model Composition
View Model Composition
SeekBar View
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:bind="http://schemas.android.com/apk/res-auto">

<data>

<import type="android.view.View" />

<variable

name="viewModel"

type="com.github.wtopolski.libmvvm.viewmodel.SeekBarViewModel"/>

</data>



<SeekBar

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:max="@{viewModel.max}"

android:progress="@={viewModel.progress}"

android:visibility="@{viewModel.visibility ? View.VISIBLE : View.GONE}"

android:enabled="@{viewModel.enabled}" />



</layout>
View Model Composition
SeekBar View Model
public class SeekBarViewModel extends BaseViewModel {

private int progress;

private int max;

private PublishSubject<Integer> progressObservable = PublishSubject.create();



public SeekBarViewModel() { super(); }



public SeekBarViewModel(boolean enabled, boolean visibility) { super(enabled, visibility); }



public void setProgress(int progress) {

this.progress = progress;

progressObservable.onNext(progress);

notifyPropertyChanged(BR.progress);

}



@Bindable

public int getProgress() { return progress; }



public void setMax(int max) {

this.max = max;

notifyPropertyChanged(BR.max);

}



@Bindable

public int getMax() { return max; }



public Observable<Integer> rxProgress() { return progressObservable.asObservable(); }

}
View Model Composition
activity_color_form.xml ColorFormViewModel.java
Binding & RecycleView
We have to remember that this kind of screen has two sets of
MVVM elements. One for list screen itself. And one for every item
on the list.



colors = generateColors();



adapter = new ColorListAdapter(colors, 

getApplicationContext(), this);



ActivityColorListBinding binding;



binding = DataBindingUtil.setContentView(this, 

R.layout.activity_color_list);



ColorListViewModel viewModel = new ColorListViewModel();



binding.setViewModel(viewModel);



viewModel.configure(true, 

new DefaultItemAnimator(), 

new LinearLayoutManager(this));



viewModel.setAdapter(adapter);
https://github.com/wtopolski/androidmvvm
Binding & RecycleView
More interesting is MVVM for list elements. First of
all, our adapter is much more simple. No more
custom ViewHolders for RecycleView. All we need is
BindingViewHolder.
public class BindingViewHolder extends RecyclerView.ViewHolder {

private ViewDataBinding binding;



public BindingViewHolder(@NonNull ViewDataBinding binding) {

super(binding.getRoot());

this.binding = binding;

}



public ViewDataBinding getBinding() {

return binding;

}

}
Binding & RecycleView
onCreateViewHolder
@Override

public BindingViewHolder onCreateViewHolder(ViewGroup parent, 

int viewType) {



ActivityColorListItemBinding binding = DataBindingUtil.inflate(

LayoutInflater.from(parent.getContext()),

R.layout.activity_color_list_item, 

parent, 

false);



return new BindingViewHolder(binding);

}
Binding & RecycleView
onBindViewHolder
@Override

public void onBindViewHolder(BindingViewHolder holder, int position) {

ActivityColorListItemBinding binding = (ActivityColorListItemBinding)

holder.getBinding();

ColorListItemViewModel viewModel = binding.getViewModel();



// Init new view model object

if (viewModel == null) {

viewModel = new ColorListItemViewModel();

binding.setViewModel(viewModel);

binding.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

viewModel.setListener(listener);

}



ColorForm form = data.get(position);

viewModel.setAdapterPosition(holder.getAdapterPosition());

viewModel.setData(form);



// Immediate Binding

binding.executePendingBindings();

}
Grabbing value directly from View
Getting value from View which is not available in
ViewModel.
private void checkEnabledStateOnView() {

viewModel.confirm.setEditableObserver(new Subscriber<Boolean>() { . . . 

@Override

public void onNext(Boolean isEnabled) {

// Some code

}

});

binding.executePendingBindings();

}
bind:editableObserver="@{viewModel.editableObserver}"
@BindingAdapter({"editableObserver"})

public static void editableObserver(View view, Subscriber<Boolean> subscriber) {

if (subscriber != null) {

subscriber.onNext(view.isEnabled());

subscriber.onCompleted();

}

}
Links
• MVC VS. MVP VS. MVVM
• Model–view–viewmodel
• Approaching Android with MVVM
• Going with MVVM on Android via Data Binding
• DataBinding: how to develop Android apps faster
• Data Binding Library
• Exploring the MVC, MVP, and MVVM design patterns
• MVVMC thought experiment
• MVVM is dead, long live MVVMC!
• Comparison of Architecture presentation patterns MVP(SC),MVP(PV),PM,MVVM and MVC
• MVMMC – MVVM Grows A Controller

More Related Content

What's hot

An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
Mobile Vue.js – From PWA to Native
Mobile Vue.js – From PWA to NativeMobile Vue.js – From PWA to Native
Mobile Vue.js – From PWA to NativeMartinSotirov
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & VuexBernd Alter
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injectionEyal Vardi
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Angular Notes.pdf
Angular Notes.pdfAngular Notes.pdf
Angular Notes.pdfsagarpal60
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulationborkweb
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 

What's hot (20)

Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Express JS
Express JSExpress JS
Express JS
 
Reactjs
ReactjsReactjs
Reactjs
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Mobile Vue.js – From PWA to Native
Mobile Vue.js – From PWA to NativeMobile Vue.js – From PWA to Native
Mobile Vue.js – From PWA to Native
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
 
React js
React jsReact js
React js
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Osgi
OsgiOsgi
Osgi
 
Angular Notes.pdf
Angular Notes.pdfAngular Notes.pdf
Angular Notes.pdf
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
Angular 8
Angular 8 Angular 8
Angular 8
 

Viewers also liked

Data Binding in Action using MVVM pattern
Data Binding in Action using MVVM patternData Binding in Action using MVVM pattern
Data Binding in Action using MVVM patternFabio Collini
 
Android Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUKAndroid Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUKFabio Collini
 
Dominando o Data Binding no Android
Dominando o Data Binding no AndroidDominando o Data Binding no Android
Dominando o Data Binding no AndroidNelson Glauber Leal
 
MVVM with DataBinding on android
MVVM with DataBinding on androidMVVM with DataBinding on android
MVVM with DataBinding on androidRodrigo Bressan
 
Windows Store Development : MVVM and data binding
Windows Store Development : MVVM and data bindingWindows Store Development : MVVM and data binding
Windows Store Development : MVVM and data bindingRemon Kamel
 
Frontend Components Outside Main App by Adam Florczak
Frontend Components Outside Main App by Adam FlorczakFrontend Components Outside Main App by Adam Florczak
Frontend Components Outside Main App by Adam Florczak10Clouds
 
iOS 10 Rich Push Notifications
iOS 10 Rich Push NotificationsiOS 10 Rich Push Notifications
iOS 10 Rich Push NotificationsinFullMobile
 
Dodanie Prezentacji Z Slide Share Do Blog Engine
Dodanie Prezentacji Z Slide Share Do Blog EngineDodanie Prezentacji Z Slide Share Do Blog Engine
Dodanie Prezentacji Z Slide Share Do Blog Enginedaniel.plawgo
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android ApplicationsLokesh Ponnada
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskHoang Ngo
 
Testable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVMTestable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVMFabio Collini
 
MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )Ahmed Emad
 
FFMPEG on android
FFMPEG on androidFFMPEG on android
FFMPEG on androidYoss Cohen
 

Viewers also liked (20)

Data Binding in Action using MVVM pattern
Data Binding in Action using MVVM patternData Binding in Action using MVVM pattern
Data Binding in Action using MVVM pattern
 
Android Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUKAndroid Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUK
 
Android data binding
Android data bindingAndroid data binding
Android data binding
 
Dominando o Data Binding no Android
Dominando o Data Binding no AndroidDominando o Data Binding no Android
Dominando o Data Binding no Android
 
MVVM with DataBinding on android
MVVM with DataBinding on androidMVVM with DataBinding on android
MVVM with DataBinding on android
 
MVVM_Ashraf
MVVM_AshrafMVVM_Ashraf
MVVM_Ashraf
 
Windows Store Development : MVVM and data binding
Windows Store Development : MVVM and data bindingWindows Store Development : MVVM and data binding
Windows Store Development : MVVM and data binding
 
Frontend Components Outside Main App by Adam Florczak
Frontend Components Outside Main App by Adam FlorczakFrontend Components Outside Main App by Adam Florczak
Frontend Components Outside Main App by Adam Florczak
 
iOS 10 Rich Push Notifications
iOS 10 Rich Push NotificationsiOS 10 Rich Push Notifications
iOS 10 Rich Push Notifications
 
Dodanie Prezentacji Z Slide Share Do Blog Engine
Dodanie Prezentacji Z Slide Share Do Blog EngineDodanie Prezentacji Z Slide Share Do Blog Engine
Dodanie Prezentacji Z Slide Share Do Blog Engine
 
Data binding
Data bindingData binding
Data binding
 
Prezi sucks
Prezi sucksPrezi sucks
Prezi sucks
 
Android Data Binding
Android Data BindingAndroid Data Binding
Android Data Binding
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
 
FFmpeg presentation
FFmpeg presentationFFmpeg presentation
FFmpeg presentation
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
 
Android Databinding Library
Android Databinding LibraryAndroid Databinding Library
Android Databinding Library
 
Testable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVMTestable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVM
 
MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )
 
FFMPEG on android
FFMPEG on androidFFMPEG on android
FFMPEG on android
 

Similar to MVVM Data Binding Library

Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databindingBoulos Dib
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatiasapientindia
 
The Magic of WPF & MVVM
The Magic of WPF & MVVMThe Magic of WPF & MVVM
The Magic of WPF & MVVMAbhishek Sur
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
 
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.UA Mobile
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data BindingEric Maxwell
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentationBhavin Shah
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc trainingicubesystem
 
Dialogs in Android MVVM (14.11.2019)
Dialogs in Android MVVM (14.11.2019)Dialogs in Android MVVM (14.11.2019)
Dialogs in Android MVVM (14.11.2019)Vladislav Ermolin
 
Introduction to XAML and its features
Introduction to XAML and its featuresIntroduction to XAML and its features
Introduction to XAML and its featuresAbhishek Sur
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談awonwon
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in androidInnovationM
 
Adding a view
Adding a viewAdding a view
Adding a viewNhan Do
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applicationsMilan Korsos
 

Similar to MVVM Data Binding Library (20)

Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
Knockoutjs
KnockoutjsKnockoutjs
Knockoutjs
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
 
The Magic of WPF & MVVM
The Magic of WPF & MVVMThe Magic of WPF & MVVM
The Magic of WPF & MVVM
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
 
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
 
MVC
MVCMVC
MVC
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data Binding
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Dialogs in Android MVVM (14.11.2019)
Dialogs in Android MVVM (14.11.2019)Dialogs in Android MVVM (14.11.2019)
Dialogs in Android MVVM (14.11.2019)
 
Introduction to XAML and its features
Introduction to XAML and its featuresIntroduction to XAML and its features
Introduction to XAML and its features
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
 
Adding a view
Adding a viewAdding a view
Adding a view
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applications
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

MVVM Data Binding Library

  • 1. MVVM & Data Binding Library Wojciech Topolski
  • 2. Agenda • Theory of MVVM • Data Binding Library • Custom MVVM(C) implementation • View Model Composition • Binding & RecycleView • Grabbing value directly from View • Links
  • 3. Theory of MVVM • "MVVM facilitates a separation of development of the graphical user interface from development of the business logic. The view model of MVVM is a value converter; meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the view model is more model than view, and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back- end logic around the set of use cases supported by the view.” (Wikipedia) • Model - Business data layer, it could be set of POJO objects or layer operating on database/network/ cache. Must be independent of user interface. • View - User interface. • View Model - It is responsible for converting data between Model and View, visibility of View components.
  • 4. Data Binding Library protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 MainActivityBinding binding;
 binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
 User user = new User("Test", "User");
 binding.setUser(user);
 } <layout xmlns:android="http://schemas.android.com/apk/res/android">
 <data>
 <variable name="user" type="com.example.User"/>
 </data>
 <LinearLayout ...>
 <TextView
 android:text="@{user.firstName}"/>
 <TextView
 android:text="@{user.lastName}"/>
 </LinearLayout>
 </layout> BY EXAMPLE Android Plugin for Gradle 2.1+
 https://developer.android.com/topic/libraries/data-binding/index.html
  • 5. Data Binding Library Variables and imports in <data>...</data> section.
 <?xml version="1.0" encoding="utf-8"?>
 <layout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:bind="http://schemas.android.com/apk/res-auto">
 <data>
 <import type="android.view.View" />
 <variable
 name="viewModel"
 type="com.github.wtopolski.libmvvm.viewmodel.ButtonViewModel"/>
 </data>
 
 <Button . . . />
 
 </layout> FEATURE 1 / 15
  • 6. Data Binding Library Widgets are available by binding.id expression, where id is equal to content of android:id attribute. However, android:id is not obligatory at all. <TextView android:id=“@+id/someTextView" /> ActivityMainBinding binding = DataBindingUtil.setContentView(
 this, R.layout.activity_main); 
 binding.someTextView.setText("XYZ"); FEATURE 2 / 15
  • 7. Data Binding Library Setting almost every widget XML attribute is possible. Directly by setter paired with attribute like android:enabled and view.setEnabled(boolean). Or indirectly using BindingAdapter or BindingMethods. <EditText
 android:enabled=“@{viewModel.enabled}" /> FEATURE 3 / 15
  • 8. Data Binding Library Observable variables. Every data change could be reflected to View. "You can change your data model in a background thread as long as it is not a collection." public class BaseViewModel extends BaseObservable {
 private boolean enabled;
 
 public void setEnabled(boolean enabled) {
 this.enabled = enabled;
 notifyPropertyChanged(BR.enabled);
 }
 
 @Bindable
 public boolean getEnabled() {
 return enabled;
 }
 } <EditText
 android:enabled=“@{viewModel.enabled}" /> FEATURE 4 / 15
  • 9. Data Binding Library Two-way data binding allows synchronization widget's state between user interface and passed variable. Main restriction is XML attribute must have listener indicating change of value. 
 <EditText
 android:text="@={viewModel.value}" /> FEATURE 5 / 15
  • 10. Data Binding Library EventHandling::MethodReference • "listener implementation is created when the data is bound” • "expression is processed at compile time, so if the method does not exist or its signature is not correct, you receive a compile time error.” • "method must match the parameters of the event listener” <Button
 android:onClick="@{viewModel::onButtonClick}” /> public void onButtonClick(View view) {
 // Some action
 } FEATURE 6 / 15
  • 11. Data Binding Library () -> EventHandling.ListenerBindings() • "listener implementation is created when event is triggered” • "return value must match the expected return value of the listener (unless it is expecting void)” <Button
 android:onClick=“@{() -> viewModel.onButtonClick()}” /> public void onButtonClick() {
 // Some action
 } FEATURE 7 / 15
  • 12. Data Binding Library BindingAdapter allows to set any data using custom XML attribute. The same solution helps to write attributes for custom widgets. No more attrs.xml files! @BindingAdapter({"errorEnabled"})
 public static void errorEnabled(TextInputLayout view, String value) {
 view.setError(value);
 view.setErrorEnabled(!TextUtils.isEmpty(value));
 } <android.support.design.widget.TextInputLayout
 bind:errorEnabled="@{viewModel.valueError}"> FEATURE 8 / 15
  • 13. Data Binding Library BindingMethods "Some attributes have setters that don't match by name… For example, the android:tint attribute is really associated with setImageTintList(ColorStateList), not setTint." @BindingMethods({
 @BindingMethod(
 type = "android.widget.ImageView",
 attribute = "android:tint",
 method = "setImageTintList")
 }) FEATURE 9 / 15
  • 14. Data Binding Library Converter helps to translate given value format into format which is expected by specific XML tag. @BindingConversion
 public static ColorDrawable convertColorToDrawable(String color) {
 return new ColorDrawable(Color.parseColor(color));
 } <LinearLayout
 android:background="@{viewModel.color}"> FEATURE 10 / 15
  • 15. Data Binding Library In custom XML attributes we can use application resources. <TextView
 bind:textColor="@{@color/green}" /> 
 <resources>
 <color name="green">#009900</color>
 </resources> FEATURE 11 / 15
  • 16. Data Binding Library Null Coalescing Operator <TextView
 android:text=“@{user.displayName ?? user.lastName}” /> FEATURE 12 / 15
  • 17. Data Binding Library Including layouts. More in View Model Composition section. <include
 layout="@layout/text_view"
 android:layout_width=“match_parent"
 android:layout_height=“wrap_content"
 bind:viewModel="@{viewModel.redDesc}"
 bind:textColor="@{@color/red}" /> FEATURE 13 / 15
  • 18. Data Binding Library Immediate Binding. "When a variable or observable changes, the binding will be scheduled to change before the next frame...To force execution, use the executePendingBindings() method." binding.executePendingBindings(); FEATURE 14 / 15
  • 19. Data Binding Library Data Binding doesn't use reflection. Binding classes are generated almost in real time by Android Studio, and they are part of application. You can find them in build directory. .../build/intermediates/classes/debug/package_name/databinding/* FEATURE 15 / 15
  • 20. Custom MVVM(C) implementation • Bases on Data Binding Library and RxJava • Layers: • Model - business data layer (POJO, Database, Cache, Backend) • View - user interface (XML and Binding) • View Model - conversion between displayed data and stored data (model), validation of forms, etc… • What’s about Activity and Fragment? Is it View or View Model? • Or maybe MVVMC? Where: • Controller - is responsible for global actions like open new Activities • View Model - takes care about operation on single screen https://github.com/wtopolski/androidmvvm
  • 21. View Model Composition Real app screens are complicated. Usually they contain several input and output widgets like EditText, Button, SeekBar, RecycleView, etc. It would be useful to create set of Views and View Models. And then reuse them to composite user interface.
  • 23. View Model Composition SeekBar View <?xml version="1.0" encoding="utf-8"?>
 <layout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:bind="http://schemas.android.com/apk/res-auto">
 <data>
 <import type="android.view.View" />
 <variable
 name="viewModel"
 type="com.github.wtopolski.libmvvm.viewmodel.SeekBarViewModel"/>
 </data>
 
 <SeekBar
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:max="@{viewModel.max}"
 android:progress="@={viewModel.progress}"
 android:visibility="@{viewModel.visibility ? View.VISIBLE : View.GONE}"
 android:enabled="@{viewModel.enabled}" />
 
 </layout>
  • 24. View Model Composition SeekBar View Model public class SeekBarViewModel extends BaseViewModel {
 private int progress;
 private int max;
 private PublishSubject<Integer> progressObservable = PublishSubject.create();
 
 public SeekBarViewModel() { super(); }
 
 public SeekBarViewModel(boolean enabled, boolean visibility) { super(enabled, visibility); }
 
 public void setProgress(int progress) {
 this.progress = progress;
 progressObservable.onNext(progress);
 notifyPropertyChanged(BR.progress);
 }
 
 @Bindable
 public int getProgress() { return progress; }
 
 public void setMax(int max) {
 this.max = max;
 notifyPropertyChanged(BR.max);
 }
 
 @Bindable
 public int getMax() { return max; }
 
 public Observable<Integer> rxProgress() { return progressObservable.asObservable(); }
 }
  • 26. Binding & RecycleView We have to remember that this kind of screen has two sets of MVVM elements. One for list screen itself. And one for every item on the list.
 
 colors = generateColors();
 
 adapter = new ColorListAdapter(colors, 
 getApplicationContext(), this);
 
 ActivityColorListBinding binding;
 
 binding = DataBindingUtil.setContentView(this, 
 R.layout.activity_color_list);
 
 ColorListViewModel viewModel = new ColorListViewModel();
 
 binding.setViewModel(viewModel);
 
 viewModel.configure(true, 
 new DefaultItemAnimator(), 
 new LinearLayoutManager(this));
 
 viewModel.setAdapter(adapter); https://github.com/wtopolski/androidmvvm
  • 27. Binding & RecycleView More interesting is MVVM for list elements. First of all, our adapter is much more simple. No more custom ViewHolders for RecycleView. All we need is BindingViewHolder. public class BindingViewHolder extends RecyclerView.ViewHolder {
 private ViewDataBinding binding;
 
 public BindingViewHolder(@NonNull ViewDataBinding binding) {
 super(binding.getRoot());
 this.binding = binding;
 }
 
 public ViewDataBinding getBinding() {
 return binding;
 }
 }
  • 28. Binding & RecycleView onCreateViewHolder @Override
 public BindingViewHolder onCreateViewHolder(ViewGroup parent, 
 int viewType) {
 
 ActivityColorListItemBinding binding = DataBindingUtil.inflate(
 LayoutInflater.from(parent.getContext()),
 R.layout.activity_color_list_item, 
 parent, 
 false);
 
 return new BindingViewHolder(binding);
 }
  • 29. Binding & RecycleView onBindViewHolder @Override
 public void onBindViewHolder(BindingViewHolder holder, int position) {
 ActivityColorListItemBinding binding = (ActivityColorListItemBinding)
 holder.getBinding();
 ColorListItemViewModel viewModel = binding.getViewModel();
 
 // Init new view model object
 if (viewModel == null) {
 viewModel = new ColorListItemViewModel();
 binding.setViewModel(viewModel);
 binding.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
 viewModel.setListener(listener);
 }
 
 ColorForm form = data.get(position);
 viewModel.setAdapterPosition(holder.getAdapterPosition());
 viewModel.setData(form);
 
 // Immediate Binding
 binding.executePendingBindings();
 }
  • 30. Grabbing value directly from View Getting value from View which is not available in ViewModel. private void checkEnabledStateOnView() {
 viewModel.confirm.setEditableObserver(new Subscriber<Boolean>() { . . . 
 @Override
 public void onNext(Boolean isEnabled) {
 // Some code
 }
 });
 binding.executePendingBindings();
 } bind:editableObserver="@{viewModel.editableObserver}" @BindingAdapter({"editableObserver"})
 public static void editableObserver(View view, Subscriber<Boolean> subscriber) {
 if (subscriber != null) {
 subscriber.onNext(view.isEnabled());
 subscriber.onCompleted();
 }
 }
  • 31. Links • MVC VS. MVP VS. MVVM • Model–view–viewmodel • Approaching Android with MVVM • Going with MVVM on Android via Data Binding • DataBinding: how to develop Android apps faster • Data Binding Library • Exploring the MVC, MVP, and MVVM design patterns • MVVMC thought experiment • MVVM is dead, long live MVVMC! • Comparison of Architecture presentation patterns MVP(SC),MVP(PV),PM,MVVM and MVC • MVMMC – MVVM Grows A Controller