1

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?

mannok
  • 1,712
  • 1
  • 20
  • 30

1 Answers1

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
  • 1
    Thank 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
  • 1
    I'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