0
votes

Using RxJS How can I pass new properties on the observer? So basically I want the prop "customProp" to be available to observable

const { Observable } = require('rxjs');

const observable = Observable.create(function (observer) {
    console.log(observer.customProp); //How to get this working?
    observer.next(1);
    observer.next(2);
    observer.next(3);
    setTimeout(() => {
        observer.next(4);
        observer.complete();
    }, 1000);
});

console.log('just before subscribe');
observable.subscribe({
    next: x => console.log('got value ' + x),
    error: err => console.error('something wrong occurred: ' + err),
    complete: () => console.log('done'),
    customProp: 'Hello World RxJS',
});
console.log('just after subscribe');

---->>> Output
just before subscribe
undefined //How can I get this working, please?
got value 1
got value 2
got value 3
just after subscribe
=> undefined
got value 4
done

Adding more info -- so basically I am trying to create a cold observable in which the producer needs a prop that should come from the subscriber

//Cold observable
var coldObservable = new Observable((observer) => {
    var myProducerObj = new MyProducer();
    myProducerObj.executeQuery(observer.customProp);
   // How could we get customProp over here?
});

Adding usage info --- coldObservable is DB connection function and customProp is the query that needs to be executed on the DB

1
You have XY problem. Consider explaining what exactly happens inside coldObservable. What is myProducerObj for?Estus Flask
coldObservable is DB connection function and customProp is the query that needs to be executed on the DBSandeep
Please, update the question with code that explains how myProducerObj is used. The solution depends on that.Estus Flask
@estus added the db query execute step, so lets assume myProducerObj is an object of DB connection which has method executeQuery. So the customProp should get the query from the subscriberSandeep
This depends on how observer interacts with myProducerObj besides customProp, this isn't shown. I posted an answer how this can be done in general but I'm positive this can be solved in a better way than current one. You will rarely ever need Observable constructor in well-written RxJS, it's for low-level operations.Estus Flask

1 Answers

1
votes

This is not possible without extending Observable class and this is not needed. It could be factory function:

const createObservableWithCustomProp = (customProp, observer) => {
  return new Observable((observer) => {
    var myProducerObj = new MyProducer(customProp);
    ...
  });
};

Usually there is rarely a need to construct observables manually because RxJS API provides rich feature set to create, transform and combine observables.