Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable instance emit without an observer (or subscriber ?)

I am using observable in Angular2. As I know so far, each Observable instance come with an observer(1:1), and when we emit something with observer.next(value) we can get that value with observable.subscribe((value) => {}).

var observable = Observable.create(observer => {
  observer.next(value);
}
.map(value=>{})
.catch(...)
observable.subscribe(value => {
  console.log(value);
})

How can I emit value without knowing the corresponding observer, because I want to emit value outside create function. One possible solution is save observer into some global variable but I think an observable should be enough. Any suggestion for this ??

like image 795
dttung1412 Avatar asked Mar 11 '23 20:03

dttung1412


1 Answers

You're mixing multiple things together. Observables are not in 1:1 relation with Observers (more precisely it's 1:N). If you want to be able to manually emit values you need a Subject which acts as an Observable and an Observer at the same time. Practically this means you can call its next() method and it'll propage the value to all its subscribers (Observers).

For example consider the following code in TypeScript:

import {Subject} from 'rxjs';

let source = new Subject();

source.subscribe(val => console.log('Observer 1:', val));
source.subscribe(val => console.log('Observer 2:', val));

source.next(42);
source.next('test');

This will print to console:

Observer 1: 42
Observer 2: 42
Observer 1: test
Observer 2: test

See live demo: http://plnkr.co/edit/gWMFMnPlLJVDC1pQi8pH?p=preview

Read more:

  • http://reactivex.io/intro.html
  • https://github.com/Reactive-Extensions/RxJS#resources
  • https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md

Be aware that Observable.create() is a very different animal. It takes as a parameter a function that is called every time a new Observer subscribes. That's why it take the newly subscribed Observer as an argument. In this function you can for example call next() method on the Observer to send it some default value that all subscribes need to receive.

So you probably want to use Subject instead of Observable.create().

like image 84
martin Avatar answered Apr 03 '23 17:04

martin