Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Observable that would accept arguments

Tags:

rx-java

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

For instance, I could parameterize http requests

like image 987
midnight Avatar asked Feb 09 '15 10:02

midnight


1 Answers

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.

like image 159
david.mihola Avatar answered Jan 01 '23 11:01

david.mihola