Skip to content
Advertisement

How to subscribe to date chage with Rxjs

I couldn’t find a “simple” example with Rxjs, demonstrating how we can listen to days changes as an event.

for example, let’s say that I have to execute certain methods every time we enter a new day. how can I approach this with the reactive paradigm and subscribe to time events?

Advertisement

Answer

I have solved this by creating an observable that is deferred until the subscription happens which then, calculates the time and looks for the nearest future midnight to emit an event.

function newSolarDayObserver() {
    return defer(() => {
      const timeAtSubscription = new Date();
      const nextDay = new Date();
      // get the nearest midnight in future
      nextDay.setHours(24, 0, 0, 0);
      const initialDelay = nextDay.getTime() - timeAtSubscription.getTime();
      // repeat every 24 hours and 1 minute
      const repeat = 1000 * 60 * 61 * 24;
      return timer(initialDelay, repeat);
    });
  }

this observable can then be used with the reapeatWhen operator to repeat a previous stream when a new day event is emitted.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement