Skip to content

Instantly share code, notes, and snippets.

@nosix
Created October 9, 2019 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nosix/ab51af69996e5eefbf2a0f0905742df4 to your computer and use it in GitHub Desktop.
Save nosix/ab51af69996e5eefbf2a0f0905742df4 to your computer and use it in GitHub Desktop.
How to make MutableLiveData declaration unnecessary in ViewModel.
package com.example.android.livedata
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
abstract class LiveDataEditor<R> {
fun <T> propertyOf() = LiveDataProperty<T>()
inner class LiveDataProperty<T> : ReadOnlyProperty<R, LiveData<T>> {
private val liveData = MutableLiveData<T>()
override fun getValue(thisRef: R, property: KProperty<*>): LiveData<T> = liveData
fun setValue(value: T?) {
liveData.value = value
}
fun postValue(value: T?) {
liveData.postValue(value)
}
}
}
package com.example.android.livedata
import android.os.CountDownTimer
import android.text.format.DateUtils
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.example.android.livedata.LiveDataEditor
class SampleViewModel : ViewModel() {
private val editor = object : LiveDataEditor<SampleViewModel>() {
val word = propertyOf<String>()
val score = propertyOf<Int>()
}
val word by editor.word // without databinding
val score: LiveData<Int> by editor.score // with databinding
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment