IM使用BlockingObservable遇到了一个难题。我有一种情况,我需要回调完成,完成后我可以进行改造API调用以获取数据。具体来说,我需要首先初始化支付网关sdk,然后在成功初始化后,我将进行改装调用。以下是我到目前为止的情况:
Observable.fromCallable(new Callable<PaymentStrategy>() {
@Override
public PaymentStrategy call() throws Exception {
return gatewayFactory.getPaymentStrategy("US");
}}).flatMap(new Function<PaymentStrategy, ObservableSource<PaymentStrategy>>() {
@Override
public ObservableSource<PaymentStrategy> apply(@NonNull final PaymentStrategy paymentStrategy) throws Exception {
return Observable.fromCallable(new Callable<PaymentStrategy>() {
@Override
public PaymentStrategy call() throws Exception {
/*here is important. i want it to block until init actually
gets a call back. when it does the subscriber will call
onComplete and the observable should move forward at that point*/
paymentStrategy.init(paymentInitSubscriber);
return paymentStrategy;
}
});
}}).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(paymentInitSubscriber);
似乎rxjava2没有toBlocking()调用,但我确实找到了toBlockingFirst()等和BlockingObservable类。但我不知道如何完成任务仍然。所以要明确的是,当我调用paymentStrategy.init()时,我需要observable才能阻塞,直到调用订阅者onComplete或onNext。我将订阅者作为参数传递,以便回调知道在完成时调用它。任何想法?
答案 0 :(得分:0)
我发现我最好使用Flowable并为它提供发射器。然后我可以发出onNext和onComplete等事件。
final PaymentStrategy paymentStrategy = gatewayFactory.getPaymentStrategy("US");
FlowableOnSubscribe flowableOnSubscribe = new FlowableOnSubscribe() {
@Override
public void subscribe(FlowableEmitter e) throws Exception {
FlowableEmitter initdownFlowableEmitter = e;
paymentStrategy.init(e);
/* above i pass in the emitter and i can call onNext when the call back i want completes. this pushes the stream forward to the next one below of the retrofit call */
}
};
final Flowable flowable = Flowable.create(flowableOnSubscribe, BackpressureStrategy.BUFFER);
return flowable.flatMap(new Function() {
@Override
public Object apply(@NonNull Object o) throws Exception {
PaymentApi service = mRetrofit.create(PaymentApi.class);
return service.getCards();
}
}).toObservable();
并且不要忘记在改造类中使用Flowable而不是obtableable。
似乎fromAsync已根据github notes here重命名为Flowable.create:
实际上,1.x fromEmitter(以前来自async)已重命名为Flowable.create。