Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create observable with parameters in Angular 6?

I want to create an observale which can pass some parameters in Angular 6. Below is the sample code for creating observable in Angular site https://angular.io/guide/observables, but it doesn't explain how to pass any parameters.

// Create an Observable that will start listening to geolocation updates
// when a consumer subscribes.
const locations = new Observable((observer) => {
  // Get the next and error callbacks. These will be passed in when
  // the consumer subscribes.
  const {next, error} = observer;
  let watchId;

  // Simple geolocation API check provides values to publish
  if ('geolocation' in navigator) {
    watchId = navigator.geolocation.watchPosition(next, error);
  } else {
    error('Geolocation not available');
  }

  // When the consumer unsubscribes, clean up data ready for next subscription.
  return {unsubscribe() { navigator.geolocation.clearWatch(watchId); }};
});

// Call subscribe() to start listening for updates.
const locationsSubscription = locations.subscribe({
  next(position) { console.log('Current Position: ', position); },
  error(msg) { console.log('Error Getting Location: ', msg); }
});

// Stop listening for location after 10 seconds
setTimeout(() => { locationsSubscription.unsubscribe(); }, 10000);

What I want is pass some parameters to observable when I subscribe it, I guess the definition of observable may be looks like:

const myobservable(a, b) = new Observable((observer) => {
  ...
})

Could you please tell how can I do that?

like image 660
lei lei Avatar asked Sep 20 '18 02:09

lei lei


1 Answers

You couldn't pass a parameter in to the subscribe , subscribe is a call back function which will execute when emit each value in a observable sequence.

When you subscribe , you can pass the value as a parameter in to the function not subscribe and do something with the parameter

SomeObservableFunction(10).subscribe(function(x){

});

In order to understand how observable works look at the below sample code snippet

 var observable = Observable.create(function(observer) {
      var sum = 0;
      for (var i = 1; i <= 4; i++) {
        if (i <= 3) {
          sum = sum + i;
           observer.next(i);  //You can emit each item from the observable also
        }
        if (i === 4) {
          setTimeout(
            i => {
              observer.next(sum);
              observer.complete();
            },
            5000,
            i
          );
        }
      }
    });

In this sample code, I am running a for loop and emit each value by using observer.next(value) , when the value of i become 4 you can see emiting the sum of 3 numbers and exiting the all observable sequence by simple calling observable.complete();

Observables are lazy which means , the above code never executes unless you are subcribing it.

Let's subscribe to get each value. I am removing the lamda expression to understand more clearly

 observable.subscribe({
      next: function(x) {

        console.log("got value " + x);
      },
      error: err => console.error("something wrong occurred: " + err),
      complete: function() {
         //when I become 4 it will complete
        console.log("completed");
      }
    });

In the callback function of next , you will get all the values we emitted from the observable including sum as final value and then it will execute the complete callback function.

You can simply receive each value like the below syntax also , which is similar to next callback

  observable.subscribe(function(x) {
      //here you will get all the value including sum
      console.log(x);
    });

Let me tell you one more scenario with the same sample by simply commenting one line of code. I am not emitting each value instead I want to emit the sum only from the observable and complete.

 var observable = Observable.create(function(observer) {
      var sum = 0;
      for (var i = 1; i <= 4; i++) {
        if (i <= 3) {
          sum = sum + i;
            //commented the code
        }
        if (i === 4) {
          setTimeout(
            i => {
              observer.next(sum);
              observer.complete();
            },
            5000,
            i
          );
        }
      }
    });

Now when you subscribe , you will have only one value , that is sum

 observable.subscribe(function(x) {
      //here you will get the sum
      console.log(x);
    });

Now returning to your question , to pass parameter you can wrap up the entire observable in to a function which return an observable. For example

SomeObservableFunction(someparam){
var observable = Observable.create(function(observer) {
       //I am not writing the same code block here 
    });
return observable;
}
like image 140
Jameel Moideen Avatar answered Nov 15 '22 08:11

Jameel Moideen