创建一个可以接受参数的 Observable [英] Create an Observable that would accept arguments

查看:52
本文介绍了创建一个可以接受参数的 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建能够接受参数的 Observable 的正确方法是什么(如果有的话)?

What is the proper way, if any, to create Observables that are capable of accepting parameters?

例如,我可以参数化 http 请求

For instance, I could parameterize http requests

推荐答案

您可以使用 Observable.create :

public static Observable<String> createMyObservable(final String all, final Integer my, final Boolean parameters) {
    return new Observable.create(new Observable.OnSubscribe<String>(){

        @Override
        public void call(Subscriber<? super String> subscriber) {
            // here you have access to all the parameters you passed in and can use them to control the emission of items:

            subscriber.onNext(all);
            if (parameters) {
                subscriber.onError(...);
            } else {
                subscriber.onNext(my.toString());
                subscriber.onCompleted();
            }
        }
    });
}

请注意,所有参数都必须声明为 final,否则代码将无法编译.

Note that all parameters must be declared as final or the code will not compile.

如果您希望您的输入参数随时间变化,它们本身可能是一个 Observable,您可以使用 combineLatestzip 将它们的值与您的其他 observable 结合起来,或者可能 mapflatMap 根据输入的 Observables 的值创建新的 Observables.

If you expect your input parameters to vary over time they may be an Observable themselves and you could maybe use combineLatest or zip to combine their values with your other observables, or possibly map or flatMap to create new Observables based on the values of your input Observables.

这篇关于创建一个可以接受参数的 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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