如何创建自定义订阅服务器?

时间:2016-01-16 11:26:44

标签: java android rx-java rx-android

我想在progressDialog正在下载文件时显示observable,完成后想要将文件发送给订阅者。

我尝试通过Subscriber扩展来制作我的自定义订阅者,例如:

public abstract class MySubscriber<T> extends Subscriber {
    abstract void onMessage(String message);
    abstract void onDownloaded(File file);
}

并尝试订阅它: `

MySubscriber mySubscriber = new MySubscriber() {
            @Override
            public void onMessage(String message) {
                progessDialog.setMessage(message);
            }

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Object o) {

            }
        };

observable.subscribe(mySubscriber);

可观察到的是:

observable  = Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<Void> subscriber) {
                 //file downloading code...
                if (subscriber instanceof MySubscriber){
                ((MySubscriber) subscriber).onMessage("100%");
                ((MySubscriber) subscriber).onDownloaded(file);
               }else{
                   Log.e(TAG,"subscriber is not instance of MySubscriber")
                }
             }

答案是“订阅者不是MySubscriber的实例”

1 个答案:

答案 0 :(得分:3)

subscriber不属于MySubscriber类型的原因是因为您传递的实例最终由SafeSubscriber中的subscribe()包裹:

private static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) {
    ...
        if(!(subscriber instanceof SafeSubscriber)) {
            subscriber = new SafeSubscriber((Subscriber)subscriber);
        }
    ...
    }
}

如果您想继续使用您的方法,可以将subscriber投射到SafeSubscriber并在其上调用SafeSubscriber#getActual()以获取MySubscriber的实例。

在你的情况下:

Observable.create(new Observable.OnSubscribe<Void>() {
    @Override
    public void call(Subscriber<? super Void> subscriber) {
        Subscriber yourSubscriber = ((SafeSubscriber) subscriber).getActual();
        ((MySubscriber) yourSubscriber).onMessage("100%");
        ((MySubscriber) yourSubscriber).onDownloaded(file);
    }
});