Zachscs
Zachscs

Reputation: 3673

How to convert an observable to it's type?

If I have an Observable<T> is there a way to convert it to T?

i.e.

let sum$: Observable<number>;
let sumNum: number;

how can I have sumNum be set to the value in sum$?

I have found that sum$.subscribe(sum => sumNum = sum); will do it but it creates a subscription which is not what I want. I want it to set the value once and not subscribe anymore.

Upvotes: 0

Views: 83

Answers (1)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20043

If I have an Observable is there a way to convert it to T?

If I understand correctly, you want something like (the non-working!)

const value = obs$.first().value();

The answer is: no, that's not possible. Observables are streams of data over time, so such a function would have to block (which is a horrible idea – what if obs$ takes five minutes to emit?). Blocking and how to avoid it is the very reason things like promises have been born. Blocking is bad.

The correct solution is what has been mentioned in the comments:

obs$.first().subscribe(value => this.value = value);

This will create a subscription which is unsubscribed the very moment obs$ emits because first() causes the chain to complete in this case. So there is nothing to be scared of about this solution.


As a small addendum, BehaviorSubject does come with a getValue() method that synchronously returns the latest value. This can be guaranteed because it's like a ReplaySubject with an initial value, i.e., at any given point in time it had at least one emission. However, resorting to BehaviorSubject#getValue() is usually a sign of doing something wrong.

Upvotes: 1

Related Questions