How to pass null to an Observable with nullable type in RxJava 2 and Kotlin

Abhinav Nair picture Abhinav Nair · Jul 25, 2017 · Viewed 17.8k times · Source

I initialize my variable like this:-

 val user: BehaviorSubject<User?> user = BehaviorSubject.create()

But I can't do this. IDE throws an error:-

user.onNext(null)

And doing this, IDE says u will never be null:-

user.filter( u -> u!=null)

Answer

nhaarman picture nhaarman · Jul 25, 2017

As Guenhter explained, this is not possible. However, instead of proposing the null-object pattern, I'd recommend an implementation of the Optional type:

data class Optional<T>(val value: T?)
fun <T> T?.asOptional() = Optional(this)

This makes your intent much clearer, and you can use a destructuring declaration in your functions:

Observable.just(Optional("Test"))
  .map { (text: String?) -> text?.substring(1)?.asOptional() }
  .subscribe()

Using the null-object pattern here can cause more bugs than it solves.