You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin中MutableLiveData属性操作的优化方案咨询

优化ViewModel中MutableLiveData的重复代码实现

你的代码功能正常,但重复获取alarm.value并拆解属性的逻辑确实可以优化,这里提供几个实用的改进方向:

1. 提取重复的当前数据获取逻辑

把每次获取alarm.value并处理非空的逻辑抽成私有函数,避免每个方法里重复写:

class MainViewModel: ViewModel() {
    val alarm : MutableLiveData<AlarmData> = MutableLiveData(AlarmData(0, alarmType.HIGH))

    // 提取私有函数,统一获取当前AlarmData并处理非空
    private fun getCurrentAlarm(): AlarmData {
        return alarm.value ?: throw IllegalStateException("Alarm data should not be null")
    }

    fun increaseValue(){
        val current = getCurrentAlarm()
        alarm.value = AlarmData(current.alarmValue + 1, current.alarmType)
    }

    fun decreaseValue(){
        val current = getCurrentAlarm()
        alarm.value = AlarmData(current.alarmValue - 1, current.alarmType)
    }

    fun togglePriority(){
        val current = getCurrentAlarm()
        val newType = when (current.alarmType){
            alarmType.HIGH -> alarmType.LOW
            alarmType.MEDIUM -> alarmType.HIGH
            alarmType.LOW -> alarmType.MEDIUM
        }
        alarm.value = AlarmData(current.alarmValue, newType)
    }
}

2. 用Data Class的copy()方法简化对象创建

如果AlarmData还不是data class,推荐改成data class——Kotlin数据类天生适合这种仅承载数据的场景,它自带的copy()方法可以只修改需要变更的属性,大幅简化代码:
先定义AlarmData为data class:

data class AlarmData(val alarmValue: Int, val alarmType: alarmType)
enum class alarmType { HIGH, MEDIUM, LOW }

然后ViewModel里的方法可以进一步简化:

class MainViewModel: ViewModel() {
    val alarm : MutableLiveData<AlarmData> = MutableLiveData(AlarmData(0, alarmType.HIGH))

    private fun getCurrentAlarm(): AlarmData {
        return alarm.value ?: throw IllegalStateException("Alarm data should not be null")
    }

    fun increaseValue(){
        getCurrentAlarm().let { current ->
            alarm.value = current.copy(alarmValue = current.alarmValue + 1)
        }
    }

    fun decreaseValue(){
        getCurrentAlarm().let { current ->
            alarm.value = current.copy(alarmValue = current.alarmValue - 1)
        }
    }

    fun togglePriority(){
        val current = getCurrentAlarm()
        val newType = when (current.alarmType){
            alarmType.HIGH -> alarmType.LOW
            alarmType.MEDIUM -> alarmType.HIGH
            alarmType.LOW -> alarmType.MEDIUM
        }
        alarm.value = current.copy(alarmType = newType)
    }
}

这样修改后,代码重复度大幅降低,可读性和维护性也得到了提升。

内容的提问来源于stack exchange,提问作者whoosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:33:12