Search code examples
angularrxjsobservable

Get current value from Observable without subscribing (just want value one time)


How can I get the current value from an Observable without subscribing to it? I just want the current value one time and not new values as they are coming in.


Solution

  • You need to use BehaviorSubject,

    • BehaviorSubject is similar to ReplaySubject except it only remembers the last publication.
    • BehaviorSubject also requires you to provide it a default value of T. This means that all subscribers will receive a value immediately (unless it is already completed).

    It will give you the most recent value published by the Observable.

    BehaviorSubject provides a getter property named value to get the most recent value passed through it.


    StackBlitz

    • In this example the value 'a' is written to the console:

    //Declare a Subject, you'll need to provide a default value.
    const subject: BehaviorSubject<string> = new BehaviorSubject("a");
    

    USAGE:

    console.log(subject.value); // will print the current value
    

    Conceal the Subject and only expose it's value

    In case you want to conceal your BehaviorSubject and only expose it's value, let's say from a Service, you can use a getter like this.

    export class YourService {
      private subject = new BehaviorSubject('random');
    
      public get subjectValue() {
        return this.subject.value;
      }
    }