在onNext()中没有传递任何内容的Observable [英] Observable which does not pass anything in onNext()

查看:63
本文介绍了在onNext()中没有传递任何内容的Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个Observable,例如提供一个系统时钟,它不需要在onNext()中传递任何东西。我找不到允许我这样做的签名。

I would need an Observable, for example to provide a system clock, which does not need to pass anything in onNext(). I couldn't find a signature that would allow me to do that.

当然,我可以使用任何对象然后传递null,但这没有多大意义。所以我的问题是,是否有更好的方法。

Sure, I could use any object and then pass null, but that doesn't make much sense. So my question is if there is a better way to do that.

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();

            }

        })


推荐答案

如果您的,则无需在onNext 上调用 Observable 不会发出任何内容。
您可以在签名中使用 Void 并执行类似

You don't need to call onNext if your Observable doesn't emit anything. You could use Void in your signature and do something like

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());
    }
});

您可以定义一个OnCompletedObserver来简化您的Observer回调,这样您就不必重写onNext因为你不需要它。

You can define an OnCompletedObserver to simplify your Observer callback so that you don't have to override the onNext since you don't need it.

public abstract class OnCompletedObserver<T> implements Observer<T> {
    @Override
    public void onNext(T o) {

    }
}

如果我理解了你的要求那么这应该可以解决问题。

If I've understood what you're asking then this should do the trick.

这篇关于在onNext()中没有传递任何内容的Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆