我想在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的实例”
答案 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);
}
});