Last active
September 15, 2020 18:06
-
-
Save yaraki/4cbeb3be276117c07d22602ab1382b04 to your computer and use it in GitHub Desktop.
LiveData with timeout
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
/* | |
* Copyright (C) 2018 The Android Open Source Project | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
package io.github.yaraki.timeout | |
import android.arch.lifecycle.LiveData | |
import android.arch.lifecycle.MediatorLiveData | |
import android.arch.lifecycle.MutableLiveData | |
import android.os.Handler | |
import android.os.Message | |
import java.lang.ref.WeakReference | |
private class ClearLiveDataHandler(liveData: MutableLiveData<*>) : Handler() { | |
companion object { | |
const val CLEAR_LIVE_DATA = 1 | |
} | |
private val liveDataRef = WeakReference<MutableLiveData<*>>(liveData) | |
override fun handleMessage(msg: Message?) { | |
if (msg?.what == CLEAR_LIVE_DATA) { | |
liveDataRef.get()?.value = null | |
} | |
} | |
} | |
fun <T> LiveData<T>.withTimeout(timeout: Long): LiveData<T> { | |
val result = MediatorLiveData<T>() | |
val handler = ClearLiveDataHandler(result) | |
result.addSource(this) { v -> | |
result.value = v | |
handler.removeMessages(ClearLiveDataHandler.CLEAR_LIVE_DATA) | |
handler.sendMessageDelayed(Message.obtain(handler, ClearLiveDataHandler.CLEAR_LIVE_DATA), | |
timeout) | |
} | |
return result | |
} |
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
package io.github.yaraki.timeout | |
import android.arch.lifecycle.LiveData | |
import android.arch.lifecycle.MutableLiveData | |
import android.arch.lifecycle.ViewModel | |
class MainViewModel : ViewModel() { | |
private val _message = MutableLiveData<String>().apply { value = "Hello, world!" } | |
val message: LiveData<String> = _message.withTimeout(3000) | |
fun updateMessage(message: String) { | |
_message.value = message | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment