mannok
mannok

Reputation: 1851

Create a computed Subject for another Subject in ReactiveX

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?

Upvotes: 1

Views: 205

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

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.

Upvotes: 1

Related Questions