AndroidViewModel


Source link: https://github.com/inloop/AndroidViewModel

AndroidViewModel

Separating data and state handling from Fragments or Activities without lots of boilerplate-code. Reducing them to simple dumb views.

Basic idea behind this library. An instance of a ViewModel class is assigned to your Fragment or Activity during the first creation and is kept during it's life cycle, even between display orientation changes. The ViewModel instance is removed after the Fragment or Activity is completely gone (finished, popped from backstack, replaced without keeping it in backstack).

You can execute asynchronous tasks in this ViewModel instance and this class is not destroyed during orientation change. All data handling and state logic should be placed inside this class. The Fragment or Activity is just a "dumb" view.

How to implement

  1. Create an interface for your View by extending IView. We will call it IUserListView for this example.

     public interface IUserListView extends IView {
    
     public void showUsers(List<User> users);
      
    }
     
  2. Create your ViewModel class by extending AbstractViewModel. For example:

    public class UserListViewModel extends AbstractViewModel<IUserListView> {
    
     .... 
    }
    
  3. Each Fragment or Activity that you would like to associate with a ViewModel will need either to extend ViewModelActivityBase/ ViewModelBaseFragment or copy the implementation from these classes to your base activity/fragment class (in case you can't inherit directly). For example:

    public class UserListFragment extends ViewModelBaseFragment<IUserListView, UserListViewModel>
      implements IUserListView {
    
      
    }
    
  4. Also each Fragment or Activity has to call setModelView() after the View (Fragment/Activity) was created and initialized. This is usually on the end of onViewCreated (or onCreate in case of an Activity)

    @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    
    super.onViewCreated(view, savedInstanceState);
    
    ButterKnife.inject(this, view);
    
    setModelView(this);
     
    }
    

How to use

You can forward user interaction from the View into the ViewModel simply by calling:

getViewModel().onDeleteUserClicked(userId);

The same goes for the opposite direction, when your asynchronous operation in the ViewModel finished and you would like to forward data to the View to show a list for example:

getViewOptional().showUsers(userList);

The getViewOptional() method will never return null. It will return a dummy implementation in case the View is null at the moment (e.g. Fragment already destroyed, or between orientation change). You can also check if the View is not null in case you need to:

if (getView() != null) {

  getView().showUsers(userList);
 
}

Your Fragment argument Bundle and Activity intent Bundle is forwarded to the ViewModel's onCreate method, which you can override to read the initial arguments for the ViewModel.

public void onCreate(Bundle arguments, Bundle savedInstanceState) {

 long userId = arguments.getInt("user_id", -1);
 
}

Data binding support

Data binding is supported - extend ViewModelBaseBindingFragment.java instead of ViewModelBaseFragment and implement getViewModelBindingConfig() in your Fragment.

@Override public ViewModelBindingConfig getViewModelBindingConfig() {

 return new ViewModelBindingConfig(R.layout.fragment_sample_binding, getActivity());
 
}

That's it. You can then directly use ObservableField in your ViewModels. See example.

Special handling for FragmentStatePagerAdapter

The Android implementation of FragmentStatePagerAdapter is removing Fragments and storing their state. This is in contrast with FragmentPagerAdapter where the Fragments are just detached but not removed. We should be also removing ViewModels and storing their state to be consistent with this behaviour.

Use ViewModelStatePagerAdapter instead of the default FragmentStatePagerAdapter. This class is only overriding the destroyItem() method and making sure that ViewModel is removed. The state is stored/restored automatically. You can also use the standard FragmentStatePagerAdapter - in that case ViewModels will be kept in memory and removed only when you leave the screen (Activity finished or Fragment removed).

How does it work?

A unique global ID is generated for the first time your Fragment or Activity is shown. This ID is passed on during orientation changes. Opening another instance of the same Fragment or Activity will result in a different ID. The ID is unique screen identifier. A ViewModel class is created and bound to this ID. The corresponding ViewModel instance is attached to your Fragment or Activity after an orientation change or if you return to the fragment in the back stack. The ViewModel is discarded once the Fragment/Activity is not reachable anymore (activity is finished or fragment permanently removed).

Download

compile 'eu.inloop:androidviewmodel:1.3.4'

Android Studio Template

For faster creating new screens, you can use Android Studio Template

Install template

Manually:

Copy the template folder to Android Studio templates folder ( /Applications/Android Studio.app/Contents/plugins/android/lib/templates/others on Mac)

Automatically:

Run the following command to download and install the template automatically (Mac only)

curl -o androidviewmodel.zip -Lk https://github.com/inloop/AndroidViewModel/archive/master.zip && unzip androidviewmodel.zip && cp -af AndroidViewModel-master/template/AVM_Inloop/. "/Applications/Android Studio.app/Contents/plugins/android/lib/templates/other/AVM_Inloop" && rm -r AndroidViewModel-master && rm androidviewmodel.zip 

Don't forget to restart the Android Studio.

Usage

In the Android Studio right click inside the Projet window and select File > New > AndroidViewModel Inloop > AVM Fragment

Resources

SpannableTextView allows to customize the styles for a single TextView (i.e., styles, size, color) rather create a separate layout.

Houdini is a simple and humane type conversion system, which allows you to prevent a lot of unnecessary code.

Android library that simplifies passing arguments between activities using generated classes aka Screens.

Circle timer on Android platform.

SVGMapView allows to display SVG on Android platform.

Nice seekbar for Android platform.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes