How to get current value of RxJS Subject or Observable?

Cover Image for How to get current value of RxJS Subject or Observable?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to get the current value of RxJS Subject or Observable?

So, you have an Angular 2 service that uses RxJS Subject to manage the isLoggedIn status. 👍

But there's a catch - you have another component that doesn't need to subscribe to the isLoggedIn Observable, but instead needs to get its current value at a specific point in time. 🤔

Don't worry, I've got you covered! In this blog post, I will walk you through the process of getting the current value of a Subject or Observable in RxJS. Let's dive in! 🏊‍♂️

The Problem

In your example code, the isLoggedIn property is an Observable obtained from the _isLoggedInSource Subject:

isLoggedIn = this._isLoggedInSource.asObservable();

While it's great for subscribing to changes, it doesn't provide a straightforward way of getting the current value without subscribing. 😕

The Solution

To get the current value of the isLoggedIn Observable at a specific point in time, you can use the BehaviorSubject from RxJS. 🚀

A BehaviorSubject is a special type of Subject that requires an initial value and emits the current value to new subscribers.

  1. First, import the BehaviorSubject from 'rxjs/BehaviorSubject':

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
  1. Replace the _isLoggedInSource Subject with a new BehaviorSubject:

private _isLoggedInSource = new BehaviorSubject<boolean>(false);

Here, we have provided an initial value of false to the BehaviorSubject. Feel free to replace it with the initial value that suits your use case. 😉

  1. Update the isLoggedIn property:

isLoggedIn = this._isLoggedInSource.asObservable();

How it works

Now, whenever you need to get the current value of isLoggedIn, you can call the getValue() method provided by BehaviorSubject.

For example, in your component that needs the current value, you can do the following:

import { SessionStorage } from './session-storage';

@Component({
  // Component metadata...
})
export class MyComponent {
  constructor(private sessionStorage: SessionStorage) { }

  someMethod() {
    // Get the current value
    const isLoggedIn = this.sessionStorage.isLoggedIn.getValue();
    
    // Do something with isLoggedIn...
  }
}

By calling the getValue() method on isLoggedIn, you will receive the current value emitted by the BehaviorSubject. 🎉

Restructuring your code

If you find yourself needing to get the current value of an Observable at many places in your codebase, consider restructuring your code to make use of a service that exposes the BehaviorSubject directly.

For example, you can modify your SessionStorage service like this:

@Injectable()
export class SessionStorage extends Storage {
  private _isLoggedInSource = new BehaviorSubject<boolean>(false);
  isLoggedIn = this._isLoggedInSource.asObservable();

  constructor() {
    super('session');
  }

  setIsLoggedIn(value: boolean) {
    this.setItem('_isLoggedIn', value, () => {
      this._isLoggedInSource.next(value);
    });
  }

  getCurrentValue(): boolean {
    return this._isLoggedInSource.getValue();
  }
}

With this modification, you can now get the current value of isLoggedIn using getCurrentValue() directly from the service whenever needed. 🎉

Bonus Tip

To make your code even more resilient, consider providing a default value in case no initial value is emitted before the first getValue() call. You can do this by modifying the BehaviorSubject creation line like this:

private _isLoggedInSource = new BehaviorSubject<boolean>(null);

By using null as the initial value, you can easily identify if the getValue() call is made before any value is emitted.

Conclusion

And there you have it! By using BehaviorSubject, you can easily get the current value of a Subject or Observable in RxJS.

Remember to implement this solution whenever you need to retrieve the current value of an Observable at a specific point in time without subscribing.

Now, go ahead and apply this knowledge to your codebase. Happy coding! 😄


How about you? Have you ever encountered a similar situation? Let us know in the comments below! Don't forget to like and share this post with your fellow developers. 👍❤️

Until next time, keep exploring, keep learning, and keep coding! ✌️😊


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello