how to setup an rxjs subject in typescript

To set up an RxJS Subject in TypeScript, first import the Subject and Observable classes from the rxjs library:

index.ts
import { Subject, Observable } from 'rxjs';
44 chars
2 lines

Then, declare a new Subject instance:

index.ts
const mySubject = new Subject();
33 chars
2 lines

To subscribe to this Subject, use the Observable class's subscribe() method:

index.ts
mySubject.subscribe({
  next: (data) => {
    console.log('Received data:', data);
  },
  error: (error) => {
    console.error('Error occurred:', error);
  },
  complete: () => {
    console.log('Subject completed!');
  }
});
227 chars
12 lines

To emit new values to the Subject, call its next() method:

index.ts
mySubject.next('Hello, world!');
33 chars
2 lines

Finally, to ensure that the Subject is cleaned up when it's no longer needed, unsubscribe from it by calling its unsubscribe() method:

index.ts
const subscription = mySubject.subscribe(/* ... */);

// Later on...
subscription.unsubscribe();
97 chars
5 lines

gistlibby LogSnag