Daniel Stephens
Daniel Stephens

Reputation: 3229

Are RxJS observables different to observables of other languages?

I want to move data from one place, to another and consider to use an Observable. I know observables from other languages, but somehow I find them very confusing. Given is the example below from a tutorial:

const foo$ = new Observable(subscriber => {
  subscriber.next(42);
  subscriber.next(43);
});

Why does the definition of foo = ... contain the value(s)? If foo would be the observable that can be subscribed to, how are the values coming in dynamically? Why is this called like this? Shouldn't it be triggered like this:

const foo$ = new Observable();

foo.subscribe((data) => console.log(data));

foo.sendSomeData(3);

In my case I want to create an observable which one consumer subscribes to, and the other source simply pushes data.

Upvotes: 0

Views: 147

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21638

What you want is a subject or a behavior subject. A subject is both an observable and an observer so that it exposes it's next methods. The difference between the two is that a behavior subject stores the previously emitted value and new subscribers get that value on subscribing. Subscribers to a subject get a value the next time the next method is called.

const { Subject } = rxjs;

const obs$ = new Subject();

obs$.subscribe(val => { console.log(val); });

obs$.next('Hello');

setTimeout(() => { obs$.next('Later'); }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js" integrity="sha512-kN8bAZFoIra6Z7dDPNMD3efoGLn7QpOZgBcNpLwKIoBM5rXLVxt9nPHNo+4WrIsT0RBc/h2sXtN08n1ALxn4yw==" crossorigin="anonymous"></script>

Upvotes: 1

Related Questions