Created
December 8, 2017 16:19
-
-
Save nazmulidris/c9ed2e789e8201e3c11b0b23b43a017e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class StateViewModel extends AndroidViewModel { | |
| private final ScheduledExecutorService myExecutor; | |
| private String mData; // This value doesn't change after it is initialized | |
| private CounterLiveData mCounter = new CounterLiveData(); // This value changes over time | |
| public StateViewModel(Application context) { | |
| super(context); | |
| myExecutor = Executors.newSingleThreadScheduledExecutor(); | |
| myExecutor.scheduleWithFixedDelay(this::recurringTask, 0, 1, TimeUnit.SECONDS); | |
| Log.d(Tags.viewmodel.name(), "ViewModel constructor: created executor"); | |
| } | |
| // Counter | |
| public void recurringTask() { | |
| long counter = mCounter.get(); | |
| Log.d(Tags.viewmodel.name(), counter % 2 == 0 ? "task: tick" : "task: tock"); | |
| mCounter.set(counter + 1); | |
| } | |
| public CounterLiveData getCounter() { | |
| return mCounter; | |
| } | |
| // Data | |
| public void setData(String mData) { | |
| this.mData = mData; | |
| } | |
| public String getData() { | |
| if (isDataSet()) { | |
| Toast.makeText(getApplication(), "Re-using ViewModel", Toast.LENGTH_SHORT).show(); | |
| } else { | |
| setData(UUID.randomUUID().toString()); | |
| Toast.makeText(getApplication(), "This is a new ViewModel", Toast.LENGTH_SHORT).show(); | |
| } | |
| return mData; | |
| } | |
| public boolean isDataSet() { | |
| return mData != null; | |
| } | |
| @Override | |
| protected void onCleared() { | |
| super.onCleared(); | |
| myExecutor.shutdown(); | |
| Log.d(Tags.viewmodel.name(), mCounter.toString()); | |
| Log.d(Tags.viewmodel.name(), "onCleared: lifecycle of activity finished"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment