The open blogging platform. Say no to algorithms and paywalls.

How to Get the Current Value of an RxJS Subject or Observable

Get the Current Value of an RxJS Observable — Daily Angular Tips, Tricks, and Best Practices

Photo by Sharon McCutcheon on Unsplash

As a developer, there is no limit to learning. We always need to be up to date with technologies as well as the upcoming or current features which are trending in the market.

Recently, I was looking for the best way to optimize my Angular code. I have gone through a lot of articles and as we know it is limitless. Then I thought of consolidating the checklist for writing cleaner code for Angular which helped me and might help others too.

These small articles not only help you to write a better TypeScript or JavaScript code but also clear the concepts of front-end technologies. This will help you to build your strong base and can help you in the upcoming front-end interviews.

Let’s move towards our main discussion

One of the most basic topics in frontend development is the proper use of RxJS which helps to synchronize our code. We do use Observables a lot in day-to-day life such as using backend service or communicating among different components. The basic thing which comes to mind is how we get the current value of the Observable.

I have found one of the best references in the Simon_Weaver Answer.

The general rule is you should only ever get a value out of an observable with subscribe()

(or async pipe if using Angular)

**BehaviorSubject: **As BehaviorSubject holds the previous value as soon as we subscribe to it, it will send previous values or the value with which it is initialized.

[@Component](http://twitter.com/Component)({
    selector: 'my-app',
    providers: [],
    template: `
    <h3>Accessing BehaviorSubject's Value</h3>

<input [(ngModel)]="currentValue" type="text">
    <br>
    <br>

current Value is: <b>{{currentValue}}</b>
  `,
})
export class AppComponent {
    subject = new BehaviorSubject('default');

get currentValue() {
        return this.subject.value;
    }

set currentValue(v) {
        this.subject.next(v);
    }
}

Approach: 1

The better approach is always to use subscribe to get a value out.

//emit 1,2,3,4,5

const source = of(1, 2, 3, 4, 5);

//take the first emitted value then complete

const example = source.pipe(take(1));

//output: 1

const subscribe = example.subscribe(val => console.log(val));

OR

const source = from([1, 2, 3, 4, 5]);

//no arguments, emit first value

const example = source.pipe(first());

//output: "First value: 1"

const subscribe = example.subscribe(val => console.log(`First value: ${val}`));

The difference between these two beings first() will error if the stream has already been completed and take(1) will not emit any observables if the stream has completed or doesn't have a value immediately available.

Approach: 2

Instead of trying to access the value in your function, consider instead a function that creates a new Observable and doesn’t even subscribe to it!

By keeping everything as observables and using switchMap to make decisions you can create new observables that can themselves be the source of other observables.

bear$: Observable<string> = of('Beary');
lion$: Observable<string> = of('Liony');
zooOpen$: Observable<boolean> = of(true);

getZooReport() {

return this.data$.pipe(switchMap(zooOpen => {

if (zooOpen) {

return combineLatest(this.bear$, this.lion$).pipe(map(([bear, lion] => {

// this is inside 'map' so return a regular string
                 return "Welcome to the zoo! Today we have a bear called ' + bear + ' and a lion called ' + lion;
              }
          );
      }
      else {

// this is inside 'switchMap' so *must* return an observable
         return of('Sorry the zoo is closed today!');
      }

});
 }

Source: Get current value from Observable without subscribing (just want value one time) *I just want the current value one time and not new values as they are coming in… You will still use subscribe, but…*stackoverflow.com How to get the current value of RxJS Subject or Observable? *A similar-looking answer was downvoted. But I think I can justify what I’m suggesting here for limited cases. While…*stackoverflow.com

Further Reading:

A Guide to the 20 Best VSCode Extensions for Frontend Developers A comprehensive guide to the most useful extensions for VSCode for frontend developmentjavascript.plainenglish.io Top 100 Questions You Must Prepare For To Ace Your Next Angular Interview (10–20) Most Common Angular Interview Questions 2021javascript.plainenglish.io 33 JavaScript Useful Shorthands Cheat List: 2021 *Optimize your JavaScript code using modern shorthand techniques, tips, and tricks.*javascript.plainenglish.io




Continue Learning