Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableField return null after update to 3.1.0

After an update to Android Studio to 3.1.0 and kotlin version to 1.2.31, I am having problem with the Observables.

The someVm value is null.

class ViewModel1(car: Car) : BaseObservable() {

    val someVm = ObservableField<ViewModel2>(ViewModel2(car))

    shipmentVm.get()!!
}

class ViewModel2(car: Car) : ItemViewModel() {

    val car= ObservableField(car)
}

open class ItemViewModel : BaseObservable() {

    val first = ObservableField(false)
    val last = ObservableField(false)
}

Thank you very much!

like image 885
azsoftco Avatar asked Nov 08 '22 08:11

azsoftco


1 Answers

I solved this by subclassing ObservableField. FWIW, it's not valid liskov as it strengthens pre-conditions, but works fine for now.

Nulls can still creep into this class (and result in NPE), if you're using it from java.

import android.databinding.Observable
import android.databinding.ObservableField

class NonNullObservableField<T : Any>(
    value: T, vararg dependencies: Observable
) : ObservableField<T>(*dependencies) {
    init {
        set(value)
    }

    override fun get(): T = super.get()!!

    @Suppress("RedundantOverride") // Only allow non-null `value`.
    override fun set(value: T) = super.set(value)
}
like image 97
Vibin Avatar answered Nov 14 '22 22:11

Vibin