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!
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With