Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
RXJS: How do I add new values to an ovservable after creation?

Im working through the basics of observables [here][1]

The examples here show Observasbles as functions with multiple returns e.g.

import { Observable } from 'rxjs';
 
const foo = new Observable(subscriber => {
  console.log('Hello');
  subscriber.next(42);
  subscriber.next(100); // "return" another value
  subscriber.next(200); // "return" yet another
});
 
foo.subscribe(x => {
  console.log(x);
});

// outputs 42, 100, 200

Question: Is it possible to add new values to an observable AFTER it has been created e.g. something like this pseudo code:

import { Observable } from 'rxjs';
 
const foo = new Observable(subscriber => {
  subscriber.next(200);
});
 
// this is pseudocode so wont work, but is the basis of this post.
...

foo.next(400);

...

foo.subscribe(x => {
  console.log(x);
});

// is it possible to output 200 and 400 by calling next after instantiation?

Or do I need to use a Subject to do that?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You have to use Subject for this. According to documentation

Every Subject is an Observer. It is an object with the methods next(v), error(e), and complete(). To feed a new value to the Subject, just call next(theValue), and it will be multicasted to the Observers registered to listen to the Subject.

Observables do not have the next method so you can not pass values to them.

about 4 years ago · Juan Pablo Isaza Report

0

You need to use Subject or BehaviorSubject. But BehaviorSubject has an initial value, so you can try to do something like this:

var obs = new rxjs.Observable((s) => {
  s.next(42);
  s.next(100);
}); 
obs.subscribe(a => console.log(a));

var sub = new rxjs.BehaviorSubject(45);
obs.subscribe(sub); 
sub.next('new value');
sub.subscribe(a => console.log(a));

Every Subject is Observable, so you can easily convert Subject to Observable via yourSubject.asObservable().

NOTE: Don't forget to unsubscribe from observable in order to prevent memory leaks.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!