I have alot of repeated code, and since I'm fairly new to Kotlin, I want to learn and try to take advantage of it as much as possible. I have many lazily declared MutableLiveData<Int>
properties, and somewhere down the code I'm checking each one to make sure that the live data's value will never go below 0. I thought using Kotlin's delegates would work but I feel like I'm at a lost.
Here's a snippet of my declaration (defaulting the value to 0).
private val count: MutableLiveData<Int> by lazy {
MutableLiveData<Int>().also { it.value = 0 }
}
Here's a snippet of some onClickListeners.
btn_decrement.setOnClickListener {
count.value?.run {
if (this > 0) {
count.value = this - 1
}
}
}
I want to do something like the following:
private val d4Count: MutableLiveData<Int> by lazy {
MutableLiveData<Int>().also { it.value = 0 }
}
set(value) {
if (field.value?.toInt() - value < 0) field.value = 0 else field.value -= value
}
But Android Studio is giving me 2 errors:
A 'val'-property cannot have a setter. This makes sense, but is there a way to keep
count
immutable, but changeMutableLiveData<Int>
's setter to something similar as my attempt?Delegated property cannot have accessors with non-default implementations. I don't really know what this means, but I'm assuming this is key to me achieving what I want.
How do I go about doing this, or am I looking at this wrong? Is there a better way to do what I want?