Share
Architecture Components – MVVM for Android
На Google I/O 17 были представлены Android Architecture Components – библиотеки для построения некоторых элементов архитектуры приложения и решения различных проблем жизненного цикла. В рамках доклада мы рассмотрим, что получилось сделать у разработчиков Google. Мы разберем, как правильно использовать архитектурные компоненты в ваших приложениях, как с помощью них решать часто встречающиеся задачи, в чем архитектурные компоненты и MVVM отличаются от привычных подходов и как тестировать написанный код. Кроме того, мы заглянем внутрь библиотек и проанализируем наиболее интересные моменты в их реализации и узнаем, что еще из этих библиотек можно использовать в своих приложениях.
Видео https://www.youtube.com/watch?v=Q1tKMMbV3nQ&list=PLINg778NUJCqlOREzMxiNC4-d_HmN6q8-&index=21
Artur Vasilov
Transcript
79 slides
-
TL;DR ▌ This is yet another way (with part of
it in the support library) 3 -
Architecture 1. Clean Architecture 2. Not very clean architecture 3.
Custom 4. Other 4 -
Presentation layer components › Model › View › Some magical
thing › Connections between these components 8 -
Bindings › DataBinding (true way for MVVM – framework handles
binding) › Observer pattern (less true way) 10 -
MVVM vs MVP › Neither better nor worse › MVVM
is less coupled (ViewModel doesn’t have a reference to View, but Presenter does) › Observing changes could be less pleasant than direct methods call › MVP has lots of implementation variants and MVVM does not 11 -
LiveData public class ExampleLiveData extends LiveData<Integer> { public void calculateValue()
{ int value = 5; //... setValue(value); } } -
Observe LiveData ExampleLiveData liveData = new ExampleLiveData(); liveData.observe(this, value ->
{ Log.i(TAG, String.format("Received value %d", value)); }); liveData.calculateValue(); -
Observe LiveData ExampleLiveData liveData = new ExampleLiveData(); liveData.observe(LifecycleOwner, value ->
{ Log.i(TAG, String.format("Received value %d", value)); }); liveData.calculateValue(); -
LifecycleOwner public interface LifecycleOwner { /** * Returns the Lifecycle
of the provider. * * @return The lifecycle of the provider. */ Lifecycle getLifecycle(); } -
Lifecycle 1. Observe lifecycle changes – this allows to remove
observer when LifecycleOwner (Activity / Fragment / Service / …) is destroyed 2. SupportActivity / Fragment (support library 26.1.0+) or LifecycleActivity / LifecycleFragment 20 -
ViewModel 1. Usual ViewModel from MVVM 2. Stored in retain
fragment (survives configuration changes) 3. Holds all important LiveData objects 4. No reference for View (View observe LiveData objects) 21 -
ViewModel example public class SimpleViewModel extends ViewModel { @NonNull private
final MutableLiveData<Integer> valueLiveData = new MutableLiveData<>(); public void init() { valueLiveData.setValue(42); } @NonNull public LiveData<Integer> observeValueChanges() { return valueLiveData; } } -
ViewModel example public class SimpleViewModel extends ViewModel { @NonNull private
final MutableLiveData<Integer> valueLiveData = new MutableLiveData<>(); public void init() { valueLiveData.setValue(42); } @NonNull public LiveData<Integer> observeValueChanges() { return valueLiveData; } } -
ViewModel example public class SimpleViewModel extends ViewModel { @NonNull private
final MutableLiveData<Integer> valueLiveData = new MutableLiveData<>(); public void init() { valueLiveData.setValue(42); } @NonNull public LiveData<Integer> observeValueChanges() { return valueLiveData; } } -
Use ViewModel SimpleViewModel simpleViewModel = ViewModelProviders.of(this).get(SimpleViewModel.class); simpleViewModel.init(); simpleViewModel.observeValueChanges().observe(this, value ->
{ Log.i(TAG, String.format("Received value %d", value)); }); -
Use ViewModel SimpleViewModel simpleViewModel = ViewModelProviders.of(this).get(SimpleViewModel.class); simpleViewModel.init(); simpleViewModel.observeValueChanges().observe(this, value ->
{ Log.i(TAG, String.format("Received value %d", value)); }); -
Use ViewModel SimpleViewModel simpleViewModel = ViewModelProviders.of(this).get(SimpleViewModel.class); simpleViewModel.init(); simpleViewModel.observeValueChanges().observe(this, value ->
{ Log.i(TAG, String.format("Received value %d", value)); }); -
Create ViewModel SimpleViewModel simpleViewModel = ViewModelProviders.of(this).get(SimpleViewModel.class); simpleViewModel.init(); simpleViewModel.observeValueChanges().observe(this, value ->
{ Log.i(TAG, String.format("Received value %d", value)); }); -
ViewModel with network call public class MoviesViewModel extends ViewModel {
//... @MainThread @NonNull LiveData<List<Movie>> getMoviesList() { if (moviesLiveData == null) { moviesLiveData = new MutableLiveData<>(); moviesRepository.popularMovies() .subscribeOn(schedulersProvider.io()) .observeOn(schedulersProvider.mainThread()) .subscribe(movies -> moviesLiveData.setValue(movies)); } return moviesLiveData; } } -
ViewModel with network call public class MoviesViewModel extends ViewModel {
//... @MainThread @NonNull LiveData<List<Movie>> getMoviesList() { if (moviesLiveData == null) { moviesLiveData = new MutableLiveData<>(); moviesRepository.popularMovies() .subscribeOn(schedulersProvider.io()) .observeOn(schedulersProvider.mainThread()) .subscribe(movies -> moviesLiveData.setValue(movies)); } return moviesLiveData; } } -
ViewModel with network call public class MoviesViewModel extends ViewModel {
//... @MainThread @NonNull LiveData<List<Movie>> getMoviesList() { if (moviesLiveData == null) { moviesLiveData = new MutableLiveData<>(); moviesRepository.popularMovies() .subscribeOn(schedulersProvider.io()) .observeOn(schedulersProvider.mainThread()) .subscribe(movies -> moviesLiveData.setValue(movies)); } return moviesLiveData; } } -
ViewModel with network call public class MoviesViewModel extends ViewModel {
//... @MainThread @NonNull LiveData<List<Movie>> getMoviesList() { if (moviesLiveData == null) { moviesLiveData = new MutableLiveData<>(); moviesRepository.popularMovies() .subscribeOn(schedulersProvider.io()) .observeOn(schedulersProvider.mainThread()) .subscribe(movies -> moviesLiveData.setValue(movies)); } return moviesLiveData; } } -
Observe values from network MoviesViewModel viewModel = getViewModel(); viewModel.getMoviesList().observe(this, movies
-> { if (movies != null) { adapter.setNewValues(movies); } }); -
ViewModel.Factory public ViewModelProvider(ViewModelStore store, Factory factory) { mFactory = factory;
this.mViewModelStore = store; } public interface Factory { /** * Creates a new instance of the given {@code Class}. * <p> * * @param modelClass a {@code Class} whose instance is requested * @param <T> The type parameter for the ViewModel. * @return a newly created ViewModel */ <T extends ViewModel> T create(Class<T> modelClass); } -
Custom factory @Inject ViewModelProvider.Factory viewModelFactory; @NonNull private MoviesViewModel getViewModel() {
return ViewModelProviders.of(this, viewModelFactory).get(MoviesViewModel.class); } -
Handling errors 1. Wrap error in custom object 2. Use
special LiveData for delivering errors 36 -
Handling errors @NonNull private final MutableLiveData<Throwable> errorsLiveData = new MutableLiveData<>();
@NonNull LiveData<Throwable> observeErrors() { return errorsLiveData; } -
Handling errors @MainThread @NonNull LiveData<List<Movie>> getMoviesList() { if (moviesLiveData ==
null) { moviesLiveData = new MutableLiveData<>(); moviesRepository.popularMovies() .subscribeOn(schedulersProvider.io()) .observeOn(schedulersProvider.mainThread()) .subscribe( movies -> moviesLiveData.setValue(movies), throwable -> errorsLiveData.setValue(throwable) ); } return moviesLiveData; } -
Testing 1. ViewModel is the only new thing to test
2. Testing is discussed many times 3. JUnit is enough 4. ViewModel testing only differs a little from Presenter testing 39 -
Unit-testing @RunWith(JUnit4.class) public class MoviesViewModelTest { private MoviesViewModel viewModel; private
MoviesRepository repository; @Before public void setUp() throws Exception { repository = Mockito.mock(MoviesRepository.class); Mockito.when(repository.popularMovies()).thenReturn(Observable.just(new ArrayList<>())); viewModel = new MoviesViewModel(schedulersProvider, repository); } } -
Unit-testing @RunWith(JUnit4.class) public class MoviesViewModelTest { @Test public void testLoadingMovies()
throws Exception { Observer observer = Mockito.mock(Observer.class); viewModel.getMoviesList().observeForever(observer); Mockito.verify(repository).popularMovies(); Mockito.verify(observer).onChanged(anyList()); } } -
Unit-testing @RunWith(JUnit4.class) public class MoviesViewModelTest { @Test public void testLoadingMovies()
throws Exception { Observer observer = Mockito.mock(Observer.class); viewModel.getMoviesList().observeForever(observer); Mockito.verify(repository).popularMovies(); Mockito.verify(observer).onChanged(anyList()); } } -
Unit-testing @RunWith(JUnit4.class) public class MoviesViewModelTest { @Test public void testLoadingMovies()
throws Exception { Observer observer = Mockito.mock(Observer.class); viewModel.getMoviesList().observeForever(observer); Mockito.verify(repository).popularMovies(); Mockito.verify(observer).onChanged(anyList()); } } -
Mock threads in LiveData @RunWith(JUnit4.class) public class MoviesViewModelTest { @Rule
public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule(); @Test public void testLoadingMovies() throws Exception { Observer observer = Mockito.mock(Observer.class); viewModel.getMoviesList().observeForever(observer); Mockito.verify(repository).popularMovies(); Mockito.verify(observer).onChanged(anyList()); } } -
Getting deeper › Common cases with Architecture Components › More
API details › Under the hood 45 -
LifecycleObserver We often have onStart / onStop and onResume /
onPause method with lots of attaching / detaching operations public class LifecycleEventsObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) void onStart() { Log.i(TAG, "onStart"); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop() { Log.i(TAG, "onStop"); } } С н цвет не ав л н -
Use LifecycleObserver public class LifecycleEventsObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) void
onStart() { Log.i(TAG, "onStart"); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop() { Log.i(TAG, "onStop"); } } getLifecycle().addObserver(new LifecycleEventsObserver()); -
LocationLiveData public class LocationLiveData extends LiveData<Location> implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START)
void startLocationUpdates() { mFusedLocationClient.requestLocationUpdates(locationRequest, callback, locationLooper); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stopLocationUpdates() { mFusedLocationClient.removeLocationUpdates(callback); } } -
LocationLiveData public class LocationLiveData extends LiveData<Location> implements LifecycleObserver { @NonNull
private final LocationCallback callback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { if (locationResult.getLastLocation() != null) { setValue(locationResult.getLastLocation()); } } }; } -
MVVM problems with DataBinding 1. Toast, dialogs, pagination and etc.
2. With Architecture Components each action is a LiveData (LiveData is like direct View method in MVP) 51 -
Send toast public class ToastViewModel extends ViewModel { @NonNull private
final MutableLiveData<String> toastMessageLiveData = new MutableLiveData<>(); @NonNull public LiveData<String> toasts() { return toastMessageLiveData; } public void doWork() { // do some work toastMessageLiveData.setValue("Hello from ViewModel"); } } -
Receive Toast @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
toastViewModel = ViewModelProviders.of(this).get(ToastViewModel.class); toastViewModel.toasts().observe(this, message -> { Toast.makeText(ToastActivity.this, message, Toast.LENGTH_SHORT).show(); }); if (savedInstanceState == null) { toastViewModel.doWork(); } } -
SingleEventLiveData public class SingleEventLiveData<T> extends MutableLiveData<T> { @NonNull private final
AtomicBoolean delivered = new AtomicBoolean(false); @Override public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) { super.observe(owner, value -> { if (delivered.compareAndSet(true, false)) { observer.onChanged(value); } }); } @Override public void setValue(@Nullable T value) { delivered.set(true); super.setValue(value); } } -
Problems 1. Duplicate events 2. When multiple parameters are required
we have to create custom objects 56 source: https://www.drupal.org/u/shalimanov -
List pagination 1. Store all items in ViewModel, join new
items and deliver all 2. Store all items in Adapter, deliver only new items 3. Paging library? 57 -
DataBinding › Google sample › Android architecture components + DataBinding
https://habrahabr.ru/company/touchinstinct/blog/330830/ 58 source: https://www.drupal.org/u/shalimanov -
ComputableLiveData 1. A LiveData class that can be invalidated &
computed on demand 2. Thread-safe (computes in background) 3. Internal class (but you can copy and use it) 61 -
ComputableLiveData ComputableLiveData<BigInteger> liveData = new ComputableLiveData<BigInteger>() { @Override protected BigInteger
compute() { return BigInteger.probablePrime(2048, new SecureRandom()); } }; liveData.getLiveData().observe(this, prime -> { Log.i(TAG, "Probable prime is " + prime); }); // call this to recompute value // liveData.invalidate(); -
Transformations 1. Map 2. SwitchMap public static <X, Y> LiveData<Y>
map(LiveData<X> source, final Function<X, Y> func) { final MediatorLiveData<Y> result = new MediatorLiveData<>(); result.addSource(source, new Observer<X>() { @Override public void onChanged(@Nullable X x) { result.setValue(func.apply(x)); } }); return result; } С н цвет не ав л н -
Custom transformations @NonNull public static <X> LiveData<X> filter(@NonNull LiveData<X> source,
@NonNull Function<X, Boolean> filterFunction) { MediatorLiveData<X> result = new MediatorLiveData<>(); result.addSource(source, input -> { if (filterFunction.apply(input)) { result.setValue(input); } }); return result; } -
No leaks for LiveData LiveData.LifecycleBoundObserver @OnLifecycleEvent(Lifecycle.Event.ON_ANY) void onStateChange() { if
(owner.getLifecycle().getCurrentState() == DESTROYED) { removeObserver(observer); return; } // immediately set active state, so we'd never dispatch anything to inactive owner activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState())) } С н цвет не ав л н -
ViewModelStore public class ViewModelStore { private final HashMap<String, ViewModel> mMap
= new HashMap<>(); final void put(String key, ViewModel viewModel) { ViewModel oldViewModel = mMap.get(key); if (oldViewModel != null) { oldViewModel.onCleared(); } mMap.put(key, viewModel); } final ViewModel get(String key) { return mMap.get(key); } } -
HolderFragment public class HolderFragment extends Fragment { private ViewModelStore mViewModelStore
= new ViewModelStore(); public HolderFragment() { setRetainInstance(true); } //... } -
HolderFragment HolderFragment holderFragmentFor(Fragment parentFragment) { FragmentManager fm = parentFragment.getChildFragmentManager(); HolderFragment
holder = findHolderFragment(fm); if (holder != null) { return holder; } holder = mNotCommittedFragmentHolders.get(parentFragment); if (holder != null) { return holder; } parentFragment.getFragmentManager() .registerFragmentLifecycleCallbacks(mParentDestroyedCallback, false); holder = createHolderFragment(fm); mNotCommittedFragmentHolders.put(parentFragment, holder); return holder; } -
LifecycleDispatcher Global handler for lifecycle events which dispatches them to
the observers class LifecycleDispatcher { static void init(Context context) { if (sInitialized.getAndSet(true)) { return; } ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new DispatcherActivityCallback()); } //... } С н цвет не ав л н -
LifecycleRuntimeTrojanProvider public class LifecycleRuntimeTrojanProvider extends ContentProvider { @Override public boolean
onCreate() { LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); return true; } //... } source: https://www.drupal.org/u/shalimanov -
LifecycleObserver under the hood 1. Code generation 2. Reflection public
class LifecycleEventsObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) void onStart() { Log.i(TAG, "onStart"); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop() { Log.i(TAG, "onStop"); } } -
Methods count & dependencies 1. 577 methods (alpha9-1) 2. Support
lib dependencies (~compat) 76 -
Summary 1. Pretty-good designed and working library 2. It’s still
alpha version 3. Good choice for newbies, pet-projects or for experiments lovers 4. Don’t change your project architecture just for Architecture Components 5. No one forces you to use MVVM (LiveData and ViewModelProviders are good enough in themselves) 77 -
Samples 1. Light sample https://github.com/ArturVasilov/ArchitecturedMovies 2. Google samples https://github.com/googlesamples/android- architecture-components
3. My largest and best project with Architecture Components is not open-source 78 -
+7 917 873-48-37 [email protected] Architecture Components – MVVM for Android
Artur Vasilov Android developer ArturVasilov ArturVasilov