Lifecycle val state = lifecycle.currentState 現在のライフサイクル状態を取得する val isAtLeastResumed = lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) 現在のライフサイクル状態が xx より後であるかどうか
sealed class Status { object Loading : Status() data class Success(val value: T) : Status() data class Error(val throwable: Throwable) : Status() } class RandomLoadLiveData : LiveData>() { // TODO } class MainViewModel : ViewModel() { // TODO }
class RandomLoadLiveData : LiveData>() { private val handler = Handler() private val r = Runnable { value = if (Random.nextBoolean()) { Status.Success(System.currentTimeMillis()) } else { Status.Error(IllegalStateException("failed")) } } override fun onActive() { if (value == null || value is Status.Error) { load() } } fun reload() { if (value !is Status.Loading) { load() } } private fun load() { value = Status.Loading handler.postDelayed(r, 1000) } fun cancel() { handler.removeCallbacks(r) } } class MainViewModel : ViewModel() { private val _liveData = RandomLoadLiveData() val liveData: LiveData> get() = _liveData fun reload() { _liveData.reload() } override fun onCleared() { super.onCleared() _liveData.cancel() } }