hi folks, I came to a strange behaviour with exten...
# android
r
hi folks, I came to a strange behaviour with extension fun and LiveData from Android Architecture components. I’ve created class to bypass initial null value of LiveData and added some ext fun to override methods observe and observeForever to return non-null values. The strange thing is the observe fun works fine but observeForever don’t, it still uses implementation of LiveDate instead of my ext fun 😞 . heres the code
Copy code
class DefaultValueLiveData<T>(defaultValue: T) : MutableLiveData<T>() {
    init {
        value = defaultValue
    }
}

fun <T> DefaultValueLiveData<T>.observeForever(listener: (T) -> Unit) {
    this.observeForever(Observer {
        it?.let {
            listener(it)
        }
    })
}

fun <T> DefaultValueLiveData<T>.observe(owner: LifecycleOwner, listener: (T) -> Unit) {
    this.observe(owner, Observer {
        it?.let {
            listener(it)
        }
    })
}

fun <T> DefaultValueLiveData<T>.value(): T {
    return value!!
}
and here is implementation example:
Copy code
val state = DefaultValueLiveData(State.CONTENT)
viewModel.state.observe(this) { // leads to my extension fun
            binding.stateLayout.setState(it) // it is non-null
        }

viewModel.state.observeForever { // leads to LiveDate fun instead of my ext fun
           binding.stateLayout.setState(it) // it is nullable
      }