Subject
in RX can store value and subscribed by others. May I know if there a way to make a Subject
depends on another Subject
as an computed version of the source Subject
?
Asked
Active
Viewed 160 times
1 Answers
1
In a way... yes!
It is possible to define observable streams from one another. So while it may not really make sense to create a "computed subject" from another subject, you can create an observable that depends on a subject, yielding an observable that emits whenever the source subject emits.
Example: (StackBlitz)
const user$ = new Subject<User>(); // Subject source
const greeting$ = user$.pipe( // Observable source
map(user => `Hello ${user.name}!`)
);
user$.subscribe(
val => console.log('user$: ', val)
);
greeting$.subscribe(
val => console.log('greeting$: ', val)
);
user$.next({ id: 1, name: 'mannok' });
user$.next({ id: 2, name: 'BizzyBob' });
// Output:
// > { id: 1, name 'mannok' }
// > Hello, mannok!
// > { id: 2, name 'BizzyBob' }
// > Hello, BizzyBob!
greeting$
is derived from user$
, so whenever user$
subject emits, greeting$
will also emit.

BizzyBob
- 12,309
- 4
- 27
- 51
-
1Thank so much. I love you example. btw, for anyone looking for C# solution you may use `observable.Select(/* you lambda function used to transform */)` – mannok Feb 25 '21 at 16:57
-
btw, for `Subject`, I can get its current value by accessing `.Value` (in Rx.NET). The solution you provided cannot get current value of `greeting$`. Any suggestion to retrieve current value of derived `Observable`? – mannok Feb 25 '21 at 17:05
-
1I'm not specifically familiar with `Rx.NET`, but generally observables are just streams that values flow through and the observable itself doesn't keep track of the last emitted value. Even basic `Subject`s in rxjs do not provide this functionality ([Get value from Subject?](https://stackoverflow.com/a/37089997/1858357)), but [BehaviorSubject](https://rxjs-dev.firebaseapp.com/api/index/class/BehaviorSubject) have a `getValue()` method for that purpose. However, observables derived from subjects/behavior subjects are just plain observables and don't have the `getValue()` method. :-( – BizzyBob Feb 25 '21 at 17:20