我想在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的实例”
最佳答案
subscriber
不属于MySubscriber
类型的原因是,您传递的实例最终被subscribe()
包装在 SafeSubscriber
中:
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);
}
});