我需要一个Observable,例如提供一个系统时钟,它不需要在onNext()中传递任何东西.我找不到允许我这样做的签名.
当然,我可以使用任何对象,然后传递null,但这没有多大意义.所以我的问题是,是否有更好的方法来做到这一点.
Observable.create(new Observable.OnSubscribe<Anyobject>() { // use any object in the signature
@Override public void call(Subscriber<? super Anyobject> subscriber) {
subscriber.onNext(null); // then pass null
subscriber.onCompleted();
}
})
Run Code Online (Sandbox Code Playgroud)
Mig*_*gne 40
onNext如果你Observable没有发出任何东西,你不需要打电话.您可以Void在签名中使用并执行类似的操作
Observable<Void> o = Observable.create(new Observable.OnSubscribe<Void>() {
@Override
public void call(Subscriber<? super Void> subscriber) {
// Do the work and call onCompleted when you done,
// no need to call onNext if you have nothing to emit
subscriber.onCompleted();
}
});
o.subscribe(new OnCompletedObserver<Void>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println("onError " + e.getMessage());
}
});
Run Code Online (Sandbox Code Playgroud)
您可以定义OnCompletedObserver以简化Observer回调,这样您就不必重写onNext,因为您不需要它.
public abstract class OnCompletedObserver<T> implements Observer<T> {
@Override
public void onNext(T o) {
}
}
Run Code Online (Sandbox Code Playgroud)
如果我已经理解了你的要求,那么这应该可以解决问题.
Mik*_*bel 39
如果你需要传递给onNext()之前的东西onCompleted():
Observable.<Void>just(null)
Run Code Online (Sandbox Code Playgroud)
如果你只需要onCompleted()被叫:
Observable.empty()
Run Code Online (Sandbox Code Playgroud)
RxJava 2.x不再接受空值,以下将立即产生NullPointerException或作为下游信号.
...
这意味着
Observable<Void>不能再发出任何值,只能正常终止或异常终止.API设计者可能会选择定义Observable<Object>而不保证对象将是什么(无论如何都应该是无关的)
这意味着你不能使用Void和做Observable.just(null).
使用Object或其他一些简单的类型:
Observable.just(new Object());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38049 次 |
| 最近记录: |