Skip to content

Instantly share code, notes, and snippets.

@urandom
Last active May 25, 2017 08:57
Show Gist options
  • Save urandom/ff40972439178550f1b65e386fe1aa25 to your computer and use it in GitHub Desktop.
Save urandom/ff40972439178550f1b65e386fe1aa25 to your computer and use it in GitHub Desktop.
Retained view model skeleton for using with data binding on android. Useful when you have rxjava stuff in your view model and you want it to survive configuration changes.
public class MyActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = RetainedFragment.getViewModel(
getFragmentManager(),
MyViewModel.class.getName(),
() -> new MyViewModel("Some data"));
viewModel.bind(this);
MyActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.my_activity);
binding.setViewModel(viewModel);
}
}
package org.sugr.example.viewmodel;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.SharedPreferences;
import android.os.Bundle;
public class RetainedFragment<VM extends RetainedViewModel<T>, T> extends Fragment {
private VM viewModel;
// Interface for creating a view model with a lambda
public interface Factory<VM extends RetainedViewModel<T>, T> {
VM create();
}
@Override public void onCreate(Bundle state) {
super.onCreate(state);
setRetainInstance(true);
}
@Override public void onDestroy() {
super.onDestroy();
if (viewModel != null) {
viewModel.destroy();
}
}
public void setViewModel(VM viewModel) {
this.viewModel = viewModel;
}
public VM getViewModel() {
return viewModel;
}
@SuppressWarnings("unchecked")
public static <VM extends RetainedViewModel<T>, T> VM getViewModel(FragmentManager fm,
String tag,
Factory<VM, T> factory) {
RetainedFragment<VM, T> fragment =
(RetainedFragment<VM, T>) fm.findFragmentByTag(tag);
if (fragment == null) {
fragment = new RetainedFragment<>();
fragment.setViewModel(factory.create());
// TODO: commit -> commitNow (support v24)
fm.beginTransaction().add(fragment, tag).commit();
}
return fragment.getViewModel();
}
}
package org.sugr.example.viewmodel;
import android.support.annotation.Nullable;
import rx.Observable;
import rx.subjects.PublishSubject;
public class RetainedViewModel<T> {
@Nullable protected T consumer;
private PublishSubject<Void> unbindSubject = PublishSubject.create();
private PublishSubject<Void> destroySubject = PublishSubject.create();
@Override public void bind(T consumer) {
this.consumer = consumer;
}
@Override public void unbind() {
unbindSubject.onNext(null);
consumer = null;
}
@Override public void destroy() {
destroySubject.onNext(null);
}
// Useful for stopping observable emission when an unbind happens
public <O> Observable.Transformer<O, O> takeUntilUnbind() {
return o -> o.takeUntil(unbindSubject);
}
// Similar to takeUntilUnbind, but for destroy
public <O> Observable.Transformer<O, O> takeUntilDestroy() {
return o -> o.takeUntil(destroySubject);
}
}
package org.sugr.example.ui.view.util;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.support.annotation.Nullable;
import android.view.View;
public class ViewUtil {
// Get the activity of an attached view
public static Activity getActivity(View view) {
Context context = view.getContext();
while (context instanceof ContextWrapper) {
// Non-compat context wrappers can be activities
if (context instanceof Activity) {
break;
}
context = ((ContextWrapper) context).getBaseContext();
}
if (context instanceof Activity) {
return (Activity) context;
}
throw new RuntimeException("An attached view will always have an activity context");
}
// Various checks to see if the view is actually part of the regular lifecycle, and not just part of a transition
public static boolean isAlive(View view) {
// Do nothing if the view is initialized by android studio for its preview feature.
// The tag is needed by the binding, and may be null when the view is attached
// for animation purposes, such as when leaving the activity.
return !view.isInEditMode() && view.getTag() != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment