Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullability and LiveData with Kotlin

I want to use LiveData with Kotlin and have values that should not be null. How do you deal with this? Perhaps a wrapper around LiveData? Searching for good patterns here .. As an example:

class NetworkDefinitionProvider : MutableLiveData<NetworkDefinition>() {
    val allDefinitions = mutableListOf(RinkebyNetworkDefinition(), MainnetNetworkDefinition(), RopstenNetworkDefinition())

    init {
        value = allDefinitions.first()
    }

    fun setCurrent(value: NetworkDefinition) {
        setValue(value)
    }
}

I know value will not be null when accessing - but I will always have to check for null or have these ugly !!'s around.

like image 443
ligi Avatar asked Sep 09 '17 16:09

ligi


1 Answers

I little improve answer The Lucky Coder. This implementation cannot accept null values at all.

class NonNullMutableLiveData<T: Any>(initValue: T): MutableLiveData<T>() {

    init {
        value = initValue
    }

    override fun getValue(): T {
        return super.getValue()!!
    }

    override fun setValue(value: T) {
        super.setValue(value)
    }

    fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
        observe(owner, Observer<T> { t -> body(t!!) })
    }

    override fun postValue(value: T) {
        super.postValue(value)
    }    
}
like image 174
icebail Avatar answered Sep 26 '22 21:09

icebail