Skip to content

Instantly share code, notes, and snippets.

@daeun1012
Created December 1, 2017 01:41
Show Gist options
  • Save daeun1012/ce293b49a9f90ec11bd0dd6b8226e713 to your computer and use it in GitHub Desktop.
Save daeun1012/ce293b49a9f90ec11bd0dd6b8226e713 to your computer and use it in GitHub Desktop.
public class LiveDataTimerViewModel extends ViewModel {
private static final int ONE_SECOND = 1000; //1초 스케줄링 (카운팅)
private MutableLiveData<Long> mElapsedTime = new MutableLiveData<>(); // LiveData
private long mInitialTime;
public LiveDataTimerViewModel() {
mInitialTime = SystemClock.elapsedRealtime();
Timer timer = new Timer();
// Update the elapsed time every second.
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
final long newValue = (SystemClock.elapsedRealtime() - mInitialTime) / 1000;
// setValue() cannot be called from a background thread so post to main thread.
mElapsedTime.postValue(newValue);
}
}, ONE_SECOND, ONE_SECOND);
}
/**
* LiveData ElapsedTime 를 반환한다.
*/
public LiveData<Long> getElapsedTime() {
return mElapsedTime;
}
}
public class ChronoActivity3 extends AppCompatActivity {
private LiveDataTimerViewModel mLiveDataTimerViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chrono_activity_3);
// ViewModel을 생성(등록?) 한다.
mLiveDataTimerViewModel = ViewModelProviders.of(this).get(LiveDataTimerViewModel.class);
subscribe();
}
/**
* LiveData ElapsedTime 을 구독한다.
*/
private void subscribe() {
final Observer<Long> elapsedTimeObserver = new Observer<Long>() {
@Override
public void onChanged(@Nullable final Long aLong) {
// 데이터 변경시 UI update
String newText = ChronoActivity3.this.getResources().getString(
R.string.seconds, aLong);
((TextView) findViewById(R.id.timer_textview)).setText(newText);
Log.d("ChronoActivity3", "Updating timer");
}
};
// LiveDat elapsedTime에 observer를 등록한다.
mLiveDataTimerViewModel.getElapsedTime().observe(this, elapsedTimeObserver);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment