Observable 存储最后一个值,但不能推送新值?

Observable that stores last value, but cannot push new ones?

假设我有一个 Person 接口,它有一个 name observable:

interface Person {
  Observable<String> name;
}

它的实现:

class David implements Person {
  Observable<String> name = BehaviorSubject<>.createDefault("David");
}

现在有一个问题,因为我无法获得 name observable 的当前值:

class Main {
  public static void main(String[] args) {
    Person person = PersonFactory.create();
    System.out.println(??person.name.currentValue??);
  }
}

我不想在我的界面中将名称公开为 BehaviorSubject,因为这样每个人都可以更改名称,这不是我想要的。

我有点理解 Observables 的逻辑,所以我知道它们不是为了存储任何值而设计的。那么什么是 RxJava 中的“具有当前值的不可变可观察对象”?

在Android中有一个LiveDataMutableLiveData。在我看来 MutableLiveData 相当于 BehaviorSubject,那么在 RxJava 中 LiveData 相当于什么?

定义变量类型 name 作为 David 内部的主题,并使用 hide() 方法公开为可观察对象。使用 hide 将确保外界无法调用 onNext 即改变名称。 See the docs for hide() here

class David implements Person {
  
    private PublishSubject<String> nameSubject = BehaviorSubject<>.createDefault("David");

    public Observable<String> observeName() {
        return nameSubject.hide();
    }

    // If you want the outside world to update the name
    public void setName(String name) {
        nameSubject.onNext(name)
    }
}

我决定创建自己的 LiveData,使用字段委托

interface LiveData<out T> {
    val observable: Observable<out T>
    val value: T

    fun subscribe(onNext: Consumer<in T>): Disposable = observable.subscribe(onNext)
}

class MutableLiveData<T>(initial: T) : LiveData<T> {
    private val subject: BehaviorSubject<T> = BehaviorSubject.createDefault(initial)

    override val observable: Observable<out T> = subject

    override var value: T
        get() = subject.value
        set(value) = subject.onNext(value)

    fun mutate(mutationFunction: T.() -> Unit) {
        value.mutationFunction()
        value = value
    }
}