0

我有很多重复的代码,而且由于我对 Kotlin 还很陌生,所以我想学习并尝试尽可能多地利用它。我有许多延迟声明MutableLiveData<Int>的属性,在代码的某个地方,我正在检查每个属性,以确保实时数据的值永远不会低于 0。我认为使用 Kotlin 的委托会起作用,但我觉得我迷路了。

这是我的声明片段(默认值为 0)。

    private val count: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>().also { it.value = 0 }
    }

这是一些 onClickListeners 的片段。

    btn_decrement.setOnClickListener {
        count.value?.run {
            if (this > 0) {
                count.value = this - 1
            }
        }
    }

我想做如下的事情:

    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
    }

但 Android Studio 给了我 2 个错误:

  1. 'val'-property 不能有 setter。这是有道理的,但是有没有办法保持count不可变,但是将 changeMutableLiveData<Int>的设置器更改为与我的尝试类似的东西?

  2. 委托属性不能具有非默认实现的访问器。我真的不知道这意味着什么,但我假设这是我实现我想要的东西的关键。

我该怎么做呢,还是我看错了?有没有更好的方法来做我想做的事?

4

2 回答 2

0

使用附加属性可以帮助您:

class SomeClass {
    var count = 0
        set(value) { 
            if (field - value < 0) field = 0 else field -= value
            _count.value = field
        }

    private val _count: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>().also { it.value = 0 }
    }
}

// Using additional property
val s = SomeClass()
s.count = 5 // this will set value to `count` and `_count` properties depending on the condition in the setter of `count` property.
于 2019-01-22T06:46:02.983 回答
0

首先,这不是您使用MutableLiveData. 您可以使用setValue(在主线程orpostValue 上)(在任何线程上)设置值。

val d4Count = MutableLiveData<Int>()

status.value = 4
status.postValue(4)

如果要更改 的设置器MutableLiveData,可以扩展MutableLiveData(1) 或创建设置器方法 (2)。

(1)

class CustomIntLiveData: MutableLiveData<Int>() {
    override fun setValue(value: Int?) {
        super.setValue(processValue(value))
    }

    override fun postValue(value: Int?) {
        super.postValue(processValue(value))
    }

    private fun processValue(value: Int?) : Int {
        val currentValue = this.value
        return if (currentValue == null || value == null || currentValue - value < 0) {
            0
        } else {
            currentValue - value
        }
    }
}

(2)

fun setCount(value: Int?) {
    val currentValue = d4Count.value

    if (currentValue == null || value == null || currentValue - value < 0) {
        d4Count.value = 0
    } else {
        d4Count.value = currentValue - value
    }
}

委托属性不能具有非默认实现的访问器。我真的不知道这意味着什么,但我假设这是我实现我想要的东西的关键。

这意味着你不能使用set,如果你使用by

于 2019-01-22T01:48:07.553 回答