Create an Observable that would accept arguments

佐手、 提交于 2020-01-03 11:33:20

问题


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

For instance, I could parameterize http requests


回答1:


You can use Observable.create for that:

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

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

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.



来源:https://stackoverflow.com/questions/28407277/create-an-observable-that-would-accept-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!