DEV Community

terrierscript
terrierscript

Posted on • Edited on

1 2

Dispose redux-observable interval when Hot Module reload

In case of use interval in redux-observable's epic, this observer is not remove when reload with HMR working.

This observable is not effect store, but it is feel bad.

Solution: Use Subject to fire with module.hot.dispose and stop

FYI: If you use typescript, @types/webpack-env includes module.hot type.

import { combineEpics } from "redux-observable"
import { interval, Subject } from "rxjs"
import { map, takeUntil } from "rxjs/operators"

const disposer = new Subject() // Setup subject for dispose.

export const timerEpic = () => {
  return interval(1000).pipe(
    takeUntil(disposer), // stop when dispose subscribed.
    map((time) => ({
      type: "TIMER",
      value: time
    }))
  )
}

if (module.hot) {
  module.hot.dispose((data) => {
    disposer.next() // send dispose when fire HMR dispose event
  })
}

Split HMR part

You can split related HMR code like this.

// hotReload.ts
import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"

const hmrDisposer = new Subject()

export const registerDisposeHandler = (module) => {
  if (module.hot) {
    module.hot.dispose(() => hmrDisposer.next())
  }
}

export const takeUntilHotReload = () => takeUntil(hmrDisposer)

Attention, you need call dispose hook on rootEpic file.

export const rootEpic = combineEpics(pingEpic)

// DO WRITE with ROOT EPIC.
registerDisposeHandler(module)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay