Search code examples
androidkotlinandroid-architecture-componentsandroid-livedata

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.


Solution

  • I created an extension property. It's not super pretty, but it is pretty straightforward.

    val <T> LiveData<T>.valueNN
        get() = this.value!!
    

    Usage

    spinner.loading = myLiveData.valueNN.homeState.loading
    

    I'm not sold on appending "NN" as a good naming convention, but that's beyond the scope of the question :)