2

it is possible (and correct) to create a custom observable ? For example, if i have data in my cache, i would like create custom observable before make a http request:

my request:

private device: Device;
getDeviceById(deviceId): Observable<Device> {
    if(this.device._id == deviceId) {
        let myObservable = new Observable('with my device'); 
        return myObservable;
    } else return this.http.get('/api/device/get/'+deviceId)
                .map(res => res.json())
                .catch(this.handleError);
}

Thank's

julien dumortier
  • 1,303
  • 1
  • 13
  • 28
  • I don't understand what's the problem. Why you couldn't create a custom Observable? Or you want to use an observable instead of the `http` request? – martin Sep 28 '16 at 11:55

4 Answers4

0

Yes, you can create one subject to work as observable as explained on answer can i emmit the event from parent to child and use it when you have data in your cache.

Community
  • 1
  • 1
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
0

You can do the following:

getDeviceById(deviceId): Observable<Device> {
if(this.authProvider == deviceId) {
    return Observable.create(observer => {
        observer.next("something");
        observer.complete();
    });
} else return this.http.get('/api/device/get/'+deviceId)
            .map(res => res.json())
            .catch(this.handleError);
lbrahim
  • 3,710
  • 12
  • 57
  • 95
0

you can do something like this:

var button = document.querySelector('button');

var subscription = Rx.Observable.create(function(obs) {
  button.onclick = function(event) {
  obs.next(event);
}
.subscribe(function(value) {
   console.log(value);
},);

see more in that link: http://reactivex.io/documentation/operators/create.html

Shmulik
  • 134
  • 2
  • 10
0

There are two main methods to create Observables in RxJS. Subjects and Operators.

See Below Example:

const obs$ = Observable.create((observer) => {
  observer.next(1);
  observer.next(2);
  //Will Thorow error
 //observer.error(new Error("Limit Exceed"));
  observer.next(3);
  //To stop execution after 
  observer.complete();
});

//Handle Subscription
custObs1.subscribe(
      (res) => {
        console.log(res);
        this._desingUtility.print(res, "elContainer");
      },
      (error) => {
        this.status = "error";
      },
      () => {
        this.status = "completed";
      }
    );

//OutPut : 
1
2
3

https://www.tutscoder.com/post/custom-observable

jignesh kumar
  • 409
  • 1
  • 4
  • 6
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31180126) – Ervin Szilagyi Mar 05 '22 at 18:08