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)

这样做,IDE说u永远不会为空:-

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

推荐答案

Thank you very much for all your answers but I ultimately went with this solution:-

class UserEnvelope(val user:User?) {}

And using this in the observables.

This best suited my requirements.

I am new to Kotlin so I don't know how to use Optionals. But from what I understand, I would have to typecast it to User type everytime I need to observe the values right?

Kotlin相关问答推荐

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

try 一次性插入多条记录时,JOOQ连接为空错误

为什么Kotlin有次构造函数和init块?

Gradle:无法创建 ExtensiblePolymorphicDomainObjectContainer

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

使用 Jetpack Compose 使用参数导航

返回 kotlin 中的标签和 lambda 表达式

区分函数和扩展

Kotlin 中私有集的完整语法 struct 是什么?

kotlin 单例异常是好是坏?

runBlocking 中的 deferred.await() 抛出的异常即使在被捕获后也被视为未处理

参考 Kotlin 中的 Java 接口静态字段

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

kotlin:扩展方法和空接收器

在Kotlin中传递并使用函数作为构造函数参数

Kotlin/JS,Gradle 插件:无法加载@webpack-cli/serve命令

如何在特定条件下清除jetpack数据存储数据

Kotlin:相互递归函数的尾部递归

Kotlin out-projected 类型禁止使用

如何将 CameraView 与 Jetpack Compose 一起使用?