Last active
July 20, 2017 03:25
-
-
Save yolapop/8c2084c016ce6665d1b8186164686135 to your computer and use it in GitHub Desktop.
Make ViewModel survive Activity tear down
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BaseFragment extends Fragment { | |
protected long dbId = -1; | |
protected ViewModelFactory viewModelFactory; | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
if (savedInstanceState != null) { | |
dbId = savedInstanceState.getLong("dbId", -1); | |
} | |
viewModelFactory = new ViewModelFactory(dbId); | |
} | |
@Override | |
public void onSaveInstanceState(Bundle outState) { | |
super.onSaveInstanceState(outState); | |
dbId = viewModelFactory.saveToDb(); | |
outState.putLong("dbId", dbId); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyFragment extends BaseFragment { | |
private MyViewModel state; | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
state = ViewModelProviders.of(getActivity(), viewModelFactory) | |
.get(MyViewModel.class); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ViewModelFactory implements ViewModelProvider.Factory { | |
private Object data; | |
private final long dbId; | |
public ViewModelFactory(long dbId) { | |
this.dbId = dbId; | |
} | |
@Override | |
public <T extends ViewModel> T create(Class<T> modelClass) { | |
try { | |
if (dbId > -1) { | |
data = YourTable.get(dbId, modelClass); // this is your implementation of getting data from local db | |
} | |
if (data == null) { | |
data = modelClass.newInstance(); | |
} | |
return (T) data; | |
} catch (InstantiationException e) { | |
Crashlytics.logException(e); | |
} catch (IllegalAccessException e) { | |
Crashlytics.logException(e); | |
} | |
return null; | |
} | |
public long saveToDb() { | |
long id = -1; | |
if (data != null) { | |
id = YourTable.put(data); // this is your implementation of saving to local db | |
} | |
return id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment