close

How to get current value of RxJS Subject or Observable?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to get current value of RxJS Subject or Observable? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to get current value of RxJS Subject or Observable ?

  1. How to get current value of RxJS Subject or Observable ?

    to get current value of RxJS Subject or Observable The best way to do this is using Behaviur Subject, here is an example:
    var sub = new rxjs.BehaviorSubject([0, 1]) sub.next([2, 3]) setTimeout(() => {sub.next([4, 5])}, 1500) sub.subscribe(a => console.log(a)) //2, 3 (current value) -> wait 2 sec -> 4, 5

  2. How to get current value of RxJS Subject or Observable ?

    to get current value of RxJS Subject or Observable The best way to do this is using Behaviur Subject, here is an example:
    var sub = new rxjs.BehaviorSubject([0, 1]) sub.next([2, 3]) setTimeout(() => {sub.next([4, 5])}, 1500) sub.subscribe(a => console.log(a)) //2, 3 (current value) -> wait 2 sec -> 4, 5

Method 1

Subject or Observable doesn’t have a current value. When a value is emitted, it is passed to subscribers and the Observable is done with it.

If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers.

It also has a method getValue() to get the current value.

Method 2

The best way to do this is using Behaviur Subject, here is an example:

var sub = new rxjs.BehaviorSubject([0, 1])
sub.next([2, 3])
setTimeout(() => {sub.next([4, 5])}, 1500)
sub.subscribe(a => console.log(a)) //2, 3 (current value) -> wait 2 sec -> 4, 5

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment