Talk about Alfonz library given at STRV Android Meetup in Nov/2017. Alfonz is a multi purpose library which helps to build Android app, makes the development process easier and helps to avoid boilerplate code. More info at http://alfonz.org.
• Easier development & avoid boilerplate code • In 2012: github.com/petrnohejl/Android-Templates-And-Utilities • In 2016: alfonz.org • Written in Java, compatible with Kotlin • Supports Android 4.1+ (API level 16)
can be declared in many V classes (types) • One VM instance can be used with just one V instance • I want to have one VM instance which could be shared with many V instances class UserListViewModel extends AbstractViewModel<IUserListView> class UserListFragment extends ViewModelBaseFragment<IUserListView, UserListViewModel>
VM instances • No DI support • I want to define constructors in VM and have a control over creating VM instances @Override public Class<UserListViewModel> getViewModelClass() { return UserListViewModel.class; }
V • By MVVM definition: VM should have no info about V • I want to have a VM completely independent from V if(getView() != null) { getView().showUsers(userList); }
One to many relation between VM & V (VM scope) • Control over creating new VM instances (DI support) • V has a reference to VM, VM has no idea about V • Resolve communication VM → V (events) • Resolve caching UI commands when Context is null • Resolve VM lifecycle (observing lifecycle) • Resolve passing extras, arguments and dependencies to VM (factory)
[✔] • One to many relation between VM & V (VM scope) [✔ VM scope] • Control over creating new VM instances (DI support) [✔ factory pattern] • V has a reference to VM, VM has no idea about V [✔ no getView() method] • Resolve communication VM → V (events) [✔ LiveData] • Resolve caching UI commands when Context is null [✔ LiveData event bus] • Resolve VM lifecycle (observing lifecycle) [✔ LifecycleObserver] • Resolve passing extras, arguments and dependencies to VM (factory) [✔ factory pattern & constructor in VM]
(fire and forget, not stateful) • No interface (interface segregation) • LiveData API • Run action only if Context is available and Activity is resumed • Definition of UI action in the view layer • Pass any object as an argument(s) • Support multiple event types ViewModel sendEvent() View observeEvent() showToast() ToastEvent message
in VM • Map with SingleLiveEvent instances for each event type • Event delivered even if an observer is not active • Delivered just once ViewModel sendEvent() View observeEvent() showToast() ToastEvent message
= new ObservableField<>(); public final ObservableField<MessageEntity> message = new ObservableField<>(); public void loadData() { state.set(StatefulLayout.PROGRESS); // load data from data provider... } private void onLoadData(MessageEntity m) { message.set(m); if(message.get() != null) { state.set(StatefulLayout.CONTENT); } else { state.set(StatefulLayout.EMPTY); } } }