Slide 1

Slide 1 text

The ViewModel @PreusslerBerlin a deep dive Danny Preussler

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

The ”architecture components” ViewModel like in Model-View-ViewModel ViewModel?

Slide 4

Slide 4 text

ViewModel in MVVM world

Slide 5

Slide 5 text

ViewModel in data binding

Slide 6

Slide 6 text

in new suggested architecture

Slide 7

Slide 7 text

Is MVP dead?

Slide 8

Slide 8 text

Is MVP dead? It’s like Java and Kotlin: •MVP will stay for quite some time •There is a new cooler kid in town that won’t leave Put the ViewModel behind Presenter

Slide 9

Slide 9 text

Is MVP dead? It’s like Java and Kotlin: •MVP will stay for quite some time •There is a new cooler kid in town that won’t leave Put the ViewModel behind Presenter

Slide 10

Slide 10 text

Is MVP dead? It’s like Java and Kotlin: •MVP will stay for quite some time •There is a new cooler kid in town that won’t leave Put the ViewModel behind Presenter

Slide 11

Slide 11 text

Is MVP dead? It’s like Java and Kotlin: •MVP will stay for quite some time •There is a new cooler kid in town that won’t leave Put the ViewModel behind Presenter

Slide 12

Slide 12 text

In architecture components •A ViewModel provides the data for a specific UI •The ViewModel does not know about the View! •Survives configuration change

Slide 13

Slide 13 text

In architecture components •A ViewModel provides the data for a specific UI •The ViewModel does not know about the View! •Survives configuration change

Slide 14

Slide 14 text

In architecture components •A ViewModel provides the data for a specific UI •The ViewModel does not know about the View! •Survives configuration change

Slide 15

Slide 15 text

In architecture components •Remember configuration change can be: •Rotation •Any other resize i.e. split screen •Language change

Slide 16

Slide 16 text

life cycle: rotation onCreate onStart onResume onPause onStop onDestroy onCreate onStart onResume ViewModel

Slide 17

Slide 17 text

life cycle: finish onCreate onStart onResume onPause onStop onDestroy ViewModel

Slide 18

Slide 18 text

How to use compile 'android.arch.lifecycle:runtime:1.0.0-alpha4' compile 'android.arch.lifecycle:extensions:1.0.0-alpha4’ // annotationProcessor // 'android.arch.lifecycle:compiler:1.0.0-alpha4'

Slide 19

Slide 19 text

How to use class MyViewModel extends ViewModel {

Slide 20

Slide 20 text

How to use class MyViewModel extends AndroidViewModel {

Slide 21

Slide 21 text

How to use class MyViewModel extends ObservableViewModel { Coming soon Jose Alcérreca, Google https://medium.com/@dpreussler/add-the-new-viewmodel-to-your-mvvm-36bfea86b159

Slide 22

Slide 22 text

How to use public void onCreate(...) { model = ViewModelProviders .of(this) .get(MyViewModel.class); }

Slide 23

Slide 23 text

What if… constructor arguments needed?

Slide 24

Slide 24 text

How to use class MyViewModelFactory implements ViewModelProvider.Factory { @Inject MyUseCase useCase; @Override public MyViewModel create(Class modelClass) { return new MyViewModel(useCase); } }

Slide 25

Slide 25 text

How to use ViewModelProviders .of(this, new MyViewModelFactory()) .get(MyShowsViewModel.class);

Slide 26

Slide 26 text

How to use •Always try to build your own Factory •Default factory uses newInstance() which is some hundred times slower than new calls (reflection) https://speakerdeck.com/dpreussler/comparing-dependency-injection- frameworks-and-internals-for-android •Don’t forward life cycle events!

Slide 27

Slide 27 text

How to use •Always try to build your own Factory •Default factory uses newInstance() which is some hundred times slower than new calls (reflection) https://speakerdeck.com/dpreussler/comparing-dependency-injection- frameworks-and-internals-for-android •Don’t forward life cycle events!

Slide 28

Slide 28 text

How to use •Always try to build your own Factory •Default factory uses newInstance() which is some hundred times slower than new calls (reflection) https://speakerdeck.com/dpreussler/comparing-dependency-injection- frameworks-and-internals-for-android •Don’t forward life cycle events!

Slide 29

Slide 29 text

What if… I need to clean something when destroyed?

Slide 30

Slide 30 text

What if… class MyViewModel extends ViewModel { @Override protected void onCleared() { super.onCleared(); cleanupSubscriptions(); }

Slide 31

Slide 31 text

How does it survive orientation change?

Slide 32

Slide 32 text

How does it actually work? class HolderFragment extends Fragment { public HolderFragment() { setRetainInstance(true); } …

Slide 33

Slide 33 text

How does it actually work? String HOLDER_TAG = "android.arch.lifecycle.state.StateProviderH olderFragment";

Slide 34

Slide 34 text

How does it know the activity is finishing?

Slide 35

Slide 35 text

How does it actually work? @Override public void onDestroy() { super.onDestroy(); mViewModelStore.clear(); }

Slide 36

Slide 36 text

Can I do it differently? ViewModel is not life cycle aware?

Slide 37

Slide 37 text

It just refuses to die

Slide 38

Slide 38 text

remember Never hold View or Activity references in the ViewModel!

Slide 39

Slide 39 text

Could you Write that?

Slide 40

Slide 40 text

Could you write that? •What if asked for ViewModel but fragment transaction not done yet? •You might end up with duplicates

Slide 41

Slide 41 text

Could you write that? •What if asked for ViewModel but fragment transaction not done yet? •You might end up with duplicates

Slide 42

Slide 42 text

Could you write that? static class HolderFragmentManager { private Map mNotCommittedActivityHolders = new HashMap<>(); private Map mNotCommittedFragmentHolders = new HashMap<>(); private ActivityLifecycleCallbacks mActivityCallbacks = new EmptyActivityLifecycleCallbacks() { @Override public void onActivityDestroyed(Activity activity) { HolderFragment fragment = mNotCommittedActivityHolders.remove(activity); …

Slide 43

Slide 43 text

What if Two Fragments of same Activity ask for same ViewModel.class via ViewModelProviders .of(this) .get(MyViewModel.class);

Slide 44

Slide 44 text

result Different ViewModels

Slide 45

Slide 45 text

What if Two Fragments of same Activity ask for same ViewModel.class via ViewModelProviders .of(this) .get(MyViewModel.class);

Slide 46

Slide 46 text

result •Fragment and Activity share the same FragmentManager but: •Implementation uses Activity’s FragmentManager but ChildFragmentManager for Fragments

Slide 47

Slide 47 text

What if Two Fragments of same Activity ask for same ViewModel.class via ViewModelProviders .of(getActivity()) .get(MyViewModel.class);

Slide 48

Slide 48 text

result Same ViewModel

Slide 49

Slide 49 text

Other uses cases communication layer between activities and fragments or fragments and fragments

Slide 50

Slide 50 text

Does that mean all problems are solved?

Slide 51

Slide 51 text

all problems solved? ViewModels provide a convenient way to retain data across configuration changes but they are not persisted if the application is killed by the operating system https://developer.android.com/topic/libraries/architecture/viewmodel.html#viewm odel_vs_savedinstancestate

Slide 52

Slide 52 text

but but WHY?

Slide 53

Slide 53 text

Why? The data saved via onSaveInstanceState is kept in the system process memory and the Android OS allows you to keep only a very small amount of data so it is not a good place to keep actual data for your app. TransactionTooLargeException anyone?

Slide 54

Slide 54 text

MeaNS ViewModels gives us rotation But takes away recreation

Slide 55

Slide 55 text

after The truth •Keep non-UI states in non-UI layer Not in bundle! •Use real caching strategies •Allows updating cache in background

Slide 56

Slide 56 text

after The truth •Keep non-UI states in non-UI layer Not in bundle! •Use real caching strategies •Allows updating cache in background

Slide 57

Slide 57 text

after The truth •Keep non-UI states in non-UI layer Not in bundle! •Use real caching strategies •Allows updating cache in background

Slide 58

Slide 58 text

but but EditText might have restored it’s state but the ViewModel will not now about it

Slide 59

Slide 59 text

but but Where to store the UI state?

Slide 60

Slide 60 text

store the UI state In Bundles!

Slide 61

Slide 61 text

but but Who owns the UI state?

Slide 62

Slide 62 text

store the UI state The ViewModel

Slide 63

Slide 63 text

store the UI state

Slide 64

Slide 64 text

lets tweak it class MyModelFactory implements ViewModelProvider.Factory { … public MyModelFactory(Bundle bundle) { this.bundle = bundle; } @Override public MyViewModel create(Class modelClass) { MyViewModel viewModel = new MyViewModel(); viewModel.readFrom(bundle); return viewModel; }

Slide 65

Slide 65 text

lets tweak it @Override public void onSaveInstanceState(Bundle bundle){ super.onSaveInstanceState(bundle); viewModel.writeTo(bundle); }

Slide 66

Slide 66 text

lets tweak it class BundleAwareFactory implements ViewModelProvider.Factory { Bundle bundle; ViewModelProvider.Factory provider; public BundleAwareViewModelFactory( @Nullable Bundle bundle, ViewModelProvider.Factory provider) { this.bundle = bundle; this.provider = provider; }

Slide 67

Slide 67 text

lets tweak it ... @Override public T create(final Class modelClass) { T viewModel = (T) provider.create(modelClass); if (bundle != null) { viewModel.readFrom(bundle); } return viewModel; }

Slide 68

Slide 68 text

lets tweak it public abstract class BundleableViewModel extends ViewModel { abstract void writeTo(Bundle bundle); abstract void readFrom(Bundle bundle); }

Slide 69

Slide 69 text

What if Activity needs multiple version of same ViewModel.class?

Slide 70

Slide 70 text

Extend IT so we can have unique class names ?!

Slide 71

Slide 71 text

But what if count is dynamic ?

Slide 72

Slide 72 text

SO unknown size of elements ?

Slide 73

Slide 73 text

CALLED RecyclerVIEW!

Slide 74

Slide 74 text

list item ViewModels In MVVM: •each item in RecyclerView should be backed by a ViewModel •ListViewModel and ItemViewModels •ItemViewModels normally don’t retrieve their own state so no need to extend Googles ViewModel

Slide 75

Slide 75 text

list item ViewModels In MVVM: •each item in RecyclerView should be backed by a ViewModel •ListViewModel and ItemViewModels •ItemViewModels normally don’t retrieve their own state so no need to extend Googles ViewModel

Slide 76

Slide 76 text

list item ViewModels In MVVM: •each item in RecyclerView should be backed by a ViewModel •ListViewModel and ItemViewModels •ItemViewModels normally don’t retrieve their own state so no need to extend Googles ViewModel

Slide 77

Slide 77 text

Let’s do it anyway

Slide 78

Slide 78 text

list item ViewModels public T get( Class modelClass)

Slide 79

Slide 79 text

list item ViewModels •Key could be position? public T get( String key, Class modelClass)

Slide 80

Slide 80 text

What about Changes?

Slide 81

Slide 81 text

What about Removal?

Slide 82

Slide 82 text

list item ViewModels “ViewModelProvider, which will create ViewModels via the given Factory and retain them in a ViewModelStore “

Slide 83

Slide 83 text

public class ViewModelStore { private final HashMap mMap = new HashMap<>(); final void put(String key, ViewModel viewModel) {…} final ViewModel get(String key) { …} public final void clear() {…} }

Slide 84

Slide 84 text

public class ViewModelStore { private final HashMap mMap = new HashMap<>(); final void put(String key, ViewModel viewModel) {…} final ViewModel get(String key) { …} public final void clear() {…} }

Slide 85

Slide 85 text

Store can not be overridden

Slide 86

Slide 86 text

list item ViewModels RecyclerView items and Googles ViewModel don’t fit together

Slide 87

Slide 87 text

What if Two different activities need same ViewModel.class?

Slide 88

Slide 88 text

This Does not sound like MVVM

Slide 89

Slide 89 text

Let’s do it anyway

Slide 90

Slide 90 text

Can I do it differently? •Let’s assume we build transactional flow spreading over multiple Activities and wand to keep data in ViewModel •Can not use the retained fragment approach •Need to override how the ViewModel is stored •Need to override the ViewModelStore is stored

Slide 91

Slide 91 text

Viewmodelstoreowner “A responsibility of an implementation of this interface is to retain owned ViewModelStore during the configuration changes and call ViewModelStore#clear(), when this scope is going to be destroyed.“

Slide 92

Slide 92 text

Viewmodelstoreowner public interface ViewModelStoreOwner { ViewModelStore getViewModelStore(); }

Slide 93

Slide 93 text

Viewmodelproviders /** * Utilities methods for {@link ViewModelStore} class. */ public class ViewModelProviders {

Slide 94

Slide 94 text

ViewModelproviders public static ViewModelProvider of( Fragment fragment, Factory factory) { return new ViewModelProvider( ViewModelStores.of(fragment), factory); }

Slide 95

Slide 95 text

Viewmodelstores /** * Factory methods for ViewModelStore class. */ public class ViewModelStores {

Slide 96

Slide 96 text

ViewModelstores ViewModelStore of(Fragment fragment) { return holderFragmentFor(fragment) .getViewModelStore(); }

Slide 97

Slide 97 text

lets do it new ViewModelProvider( new LongLivingViewModelStoreOwner(), new BundleAwareViewModelFactory (bundle, provider)) .get(MyViewModel.class);

Slide 98

Slide 98 text

How to extend life? Toothpick: A scope tree based Dependency Injection (DI) library https://github.com/stephanenicolas/toothpick

Slide 99

Slide 99 text

lets do it class LongLivingViewModelStoreOwner implements ViewModelStoreOwner { @Override public ViewModelStore getViewModelStore() { return Toothpick.openScope(SCOPE_NAME) .getInstance(ViewModelStore.class); } public void discardViewModel() { Toothpick.closeScope(SCOPE_NAME); }

Slide 100

Slide 100 text

let`s sum up •Well designed API •Know the life time: Never have Activivity or View reference in ViewModel •Be aware of Recreation •Careful with RecyclerView •Still alpha

Slide 101

Slide 101 text

Want to know more •https://medium.com/@dpreussler/add-the-new- viewmodel-to-your-mvvm-36bfea86b159 •https://proandroiddev.com/customizing-the-new- viewmodel-cf28b8a7c5fc •http://hannesdorfmann.com/android/arch- components-purist •https://www.techyourchance.com/android- viewmodel-architecture-component-harmful/

Slide 102

Slide 102 text

Southpark copyright Disclaimer

Slide 103

Slide 103 text

viacom.tech/link/mobileoptimized/2017/careers We are hiring

Slide 104

Slide 104 text

The ViewModel @PreusslerBerlin a deep dive Danny Preussler