Skip to content

Instantly share code, notes, and snippets.

@yaraki
Last active September 15, 2020 18:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaraki/4cbeb3be276117c07d22602ab1382b04 to your computer and use it in GitHub Desktop.
Save yaraki/4cbeb3be276117c07d22602ab1382b04 to your computer and use it in GitHub Desktop.
LiveData with timeout
/*
* 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
}
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