RxJava替代CompletableFuture

时间:2018-06-08 01:53:21

标签: android rx-java reactive-programming

我是Rx java的新手,并试图找到解决我问题的方法。我想将一个Single返回给调用者,但是当调用该方法时数据不可用,它将在调用之前或调用之后被填充。我想要做的一个天真的例子如下。 CompletableFuture部分解决了它,但我正在寻找Rx解决方案,可能还有背压。

val receiver = Receiver()

class Receiver {
    var data = ""

    // this returns a single but does not have data, but will be available after call to onComplete
    request(): Single<Data> {
        return Single.fromFuture(completableFuture)
    }

    onNext(data: String) {
        data.append(data)
    }

    onComplete() {
        completableFuture.complete(data)
    }
}

class Processor {
    fun process() {
        receiver.onNext("1")
        receiver.onNext("2")
        receiver.onComplete()
    }
}

class Caller {
    fun call() {
        // This should get "12" result
        // Processor().process() can be called before or after caller subscibe
        receiver.request()..subscribe(...)
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用CompletableFuture而不是PublishSubject。为了能够在订阅呼叫之前或之后提供值,您还应该在.cache()上使用Single。把它们放在一起像这样:

class Receiver {
    var data = ""
    val subject = PublishSubject.create<Data>()
    val single = Single.fromObservable(subject).cache()
    // this ensures there is at least one subscription when the event is published - otherwise because there is no subscriber, the event is lost, despite cache().
    val dummyObserver = single.subscribe()

    // this returns a single but does not have data, but will be available after call to onComplete
    fun request(): Single<Data> {
        return single
    }

    fun onNext(data: String) {
        // as before
    }

    fun onComplete() {
        subject.onNext(data)
        subject.onComplete(data)
    }
}