2

What's the most elegant way (in Calmm stack, Kefir, Karet Utils etc.) of doing repeated (infinite) async jobs with interval?

I want to get some json every 2000ms.

Example 1 (2000ms interval):

  1. Fetch json (get takes 100ms)
  2. Handle json
  3. Wait the remaining time left on the interval, and start again from step 1

Example 2 (2000ms interval)

  1. Fetch json (get takes 5000ms)
  2. Handle json
  3. Wait until steps 1 and 2 are finished before starting again at step 1

So in short, I want to to repeated gets (or any async work) and wait a minimum of 2000ms between requests.

I don't want the next request to fire until the previous one has finished in some way (success, fail, timeout).

pe3
  • 2,301
  • 1
  • 14
  • 11
Harri Virtanen
  • 739
  • 2
  • 8
  • 14
  • Just curious, what is "Calmm"? Or Kefir, or Karet Utils as well? – evolutionxbox Jun 15 '17 at 10:22
  • This is about `Angular` and `RXJS` but the main concept is absolutely the same, so, I think this is already answered here: https://stackoverflow.com/questions/44540703/return-promise-every-1-minute/44540833#44540833 – Hitmands Jun 15 '17 at 10:28
  • @evolutionxbox you can check calmm here https://github.com/calmm-js/documentation/blob/master/introduction-to-calmm.md – khaled alomar Jul 10 '17 at 09:08
  • @evolutionxbox Calmm is a functional reactive JavaScript framework / toolset that is idiomatically used in combination with React, but can also be used with preact and possibly other vdom libraries. Calmm makes it possible to embed observables directly in vdom. The Calmm toolset is composed of several libraries, including partial.lenses (a functional lens library) and karet.util (observables utilities library based on Kefir w/ some Ramda included). Kefir is an observables (streams and properties) library. Ramda is a popular library that facilitates a functional programming style. – tex Sep 21 '17 at 09:44

1 Answers1

1

This is how I would do that with Kefir without resorting to Kefir.stream. Note that job below would be the task you do at each tick. I stubbed a dummy task for the code to work.

let result = Kefir.repeat(() => {
    let job = Kefir.later(Math.random() * 5000);
    let wait = Kefir.later(2000).ignoreValues();
    return Kefir.merge([job, wait]);
});

Below is a visualization of the events using the style from the Kefir documentation:

spawned 1 - job:   ------1X
spawned 1 - wait:  -----------X
spawned 1 - merge: ------1----X
spawned 2 - job:               ------------------2X
spawned 2 - wait:              -----------X
spawned 2 - merge:             ------------------2X
spawned 3 - job:                                   ---3X
spawned 3 - wait:                                  -----------X
spawned 3 - merge:                                 ---3-------X
result:            ------1-----------------------2----3--------...
jcbelanger
  • 539
  • 3
  • 15