Learnitweb

Void Subject in RxJS

Sometimes the requirement is just to send a dummy value from a Subject. That is, what value is returned is irrelevant. The returned value logically represents that the event has occurred. For example, you want to keep track of every second. You can probably think of to write sometime like this:

const subject = new Subject<string>();
setTimeout(() => subject.next('dummy value'), 1000);

Sending a dummy value doesn’t look logically correct and is not a clean way of writing code. In this case a void subject can be used.

const subject = new Subject<void>();
setTimeout(() => subject.next(), 1000);

The cleaner and alternate way of writing const subject = new Subject<void>(); is const subject = new Subject();

Example

import { Subject } from "rxjs";

//void subject
const subject = new Subject(); 

subject.subscribe({
  next: () => console.log("One second timer expired"),
});

setTimeout(() => subject.next(), 1000);