midnight
midnight

Reputation: 3412

Create an Observable that would accept arguments

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

For instance, I could parameterize http requests

Upvotes: 5

Views: 3308

Answers (1)

david.mihola
david.mihola

Reputation: 13002

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.

Upvotes: 7

Related Questions