簡體   English   中英

如何創建可以保存 state 的不可為空的 LiveData

[英]How to create a non-nullable LiveData that can save state

當我們有如下的 liveData 時,我們不能_liveData.value++ ,因為該value可以為空。

class MainViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
    private val _liveData: MutableLiveData<Int> =
        savedStateHandle.getLiveData("SomeKey", 0)

    val liveData: MutableLiveData<Int> = _liveData

    fun triggerLiveData() {
        _liveData.value++
    }
}

文章https://proandroiddev.com/improving-livedata-nullability-in-kotlin-45751a2bafb7提供了解決方案,即

@Suppress("UNCHECKED_CAST")
class SafeMutableLiveData<T>(value: T) : LiveData<T>(value) {

  override fun getValue(): T = super.getValue() as T
  public override fun setValue(value: T) = super.setValue(value)
  public override fun postValue(value: T) = super.postValue(value)
}

但這不支持已保存狀態。

我們如何才能獲得一個也具有已保存狀態的不可為空的 LiveData?

我有一個復制數據但看起來不那么優雅的解決方案

@Suppress("UNCHECKED_CAST")
class SafeMutableLiveData<T: Any>(private val mutableLiveData: MutableLiveData<T>) :
    MutableLiveData<T>(mutableLiveData.value) {

    override fun getValue(): T = mutableLiveData.value as T
    override fun setValue(value: T) {
        super.setValue(value)
        mutableLiveData.value = value
    }
    override fun postValue(value: T) {
        super.postValue(value)
        mutableLiveData.postValue(value)
    }
}

用法如下

class MainViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
    private val _liveData: SafeMutableLiveData<Int> =
        SafeMutableLiveData(savedStateHandle.getLiveData("Something", 0))

    val liveData: SafeMutableLiveData<Int> = _liveData

    fun triggerLiveData() {
        _liveData.value++
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM