how to use the subscriber function from the rxjs library in typescript

The subscribe() function in the RxJS library is used for executing any observable, and it takes an argument of type Subscriber<T>.

Here's how to use subscribe() function with a simple example:

index.ts
import { Observable } from 'rxjs';

const observable = new Observable<number>(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  subscriber.complete();
});

observable.subscribe({
  next(x) { console.log(`Next: ${x}`); },
  error(err) { console.error(`Error: ${err}`); },
  complete() { console.log('Completed'); }
});
352 chars
15 lines

In the code above, we create an observable that emits three sequential numbers, then completes. We then pass an object to the subscribe() function that defines three functions: next(), error(), and complete().

The next() function is called every time a value is emitted, and the error() function is called if something goes wrong while emitting. Finally, the complete() function is called when the observable completes its work.

Note that the object passed to subscribe() is optional. If you don't provide it, the subscribe() function will run the observable but won't take any further action.

gistlibby LogSnag