FutureCallback到Observable

时间:2017-06-17 07:15:45

标签: java callback rx-java observable

有没有办法从FutureCallback创建Observable?我看到Observable.create已被弃用,并且不是正确的方法(下图)。

我正在转换

Observable.create(new Observable.OnSubscribe<HttpResponse>() {
        @Override
        public void call(Subscriber<? super HttpResponse> subscriber) {
            getClient().execute(httpRequest, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse response) {
                    subscriber.onNext(response);
                    subscriber.onCompleted();
                }
                @Override
                public void failed(Exception ex) {
                    subscriber.onError(ex);
                }
                @Override
                public void cancelled() {
                    subscriber.onError(new Exception());
                }
            });
        }
})

1 个答案:

答案 0 :(得分:2)

使用其他create overload

Observable.<Event>create(emitter -> {
    Callback listener = new Callback() {
        @Override
        public void onEvent(Event e) {
            emitter.onNext(e);
            if (e.isLast()) {
                emitter.onCompleted();
            }
        }

        @Override
        public void onFailure(Exception e) {
            emitter.onError(e);
        }
    };

    AutoCloseable c = api.someMethod(listener);

    emitter.setCancellation(c::close);

}, BackpressureMode.BUFFER);