Skip to content

Lifecycle management

Sasa Sekulic edited this page Mar 30, 2016 · 4 revisions

There are two basic components in this library whose lifecycle you should manage, ViewBinder and ViewModel.

ViewBinder

In the current examples, we have created the ViewBinder in the Activity's onCreate() and destroyed it in the Activity's onDestroy(). This was done for illustration only! ViewBinder should have a global lifecycle. You can either create it as a static instance in your Application instance or, if you use Dagger, you should provide it as a singleton. The idea is to create the ViewBinder exactly once in your app and then reuse it in all the activities/fragments.

ViewModel

In the current examples, ViewModel lifecycle corresponds to that of the parent Activity. For that purpose, ViewModel has lifecycle methods: onCreate(Bundle), onResume(), onPause(), onSaveInstanceState(Bundle) and dispose().

If you use one of the library's binding activity classes (BindingActivity, BindingFragmentActivity, BindingActionBarActivity, BindingAppCompatActivity), ViewModel lifecycle is already managed internally. If you use Android's regular classes, you have to manage the lifecycle manually.

If your app supports orientation change and you would like to speed up the view refreshing after orientation change, you can also keep the ViewModel reference elsewhere (outside of Activity), but then you have to clear the bindings manually when the view is destroyed calling IViewBinder.clearBindingsFor(View). Views will get bound again when inflating, and you don't have to recreate the ViewModel.