Search code examples
javascriptreactjsreduxredux-sagathrottling

Emit throttled file load progress in redux-saga through eventChannel


I'm using redux-saga with eventChannel in order to handle resource loading with progress tracking.

I was wondering what's the best pattern in order to debounce load-progress event that are too frequent. Am I supposed to handle that at a lower level with a throttled emission

import {
  eventChannel,
  END
} from 'redux-saga'
import request from 'superagent';
import { throttle } from 'throttle-debounce';



function loadFile(url) {
  return eventChannel(emitter => {

    const emitProgress = (emitter, payload) => emitter(payload);
    const emitProgressThrottled = throttle(500, emitProgress);

    request.post(url)
      .on('progress', event => {
        const payload = {
          percent: event.percent,
          type: 'progress'
        };

        emitProgressThrottled(emitter, payload)            

      })
      .then(res => {
        const payload = {
          data: res.body,
          type: 'finish'
        };

        emitter(payload);
        emitter(END);
      })
  })
}

or is it better to handle that within redux-saga scope throttling the inbound pattern emitted by eventChannel?

Any help appreciated. Thanks.


Solution

  • A couple pf weeks have passed since I originally posted the question and I made my thoughts clearer.

    For the described scenario I preferred the lower level throttle approach (code in the above question body). Isolating the API operational scope as well as avoiding additional load to the redux-saga middleware seems more reasonable to me.

    As @Martin Kadlec correctly pointed out, both solution are to be considered acceptable. Which one you'll choose is bonded more with software design patterns and personal preferences.