[Compose] Concurrency + Channel and Reactive programming for JS

Concurrency + Channel (CSP):

Concurrency is a way to run operation in isolated thread, a way to better utilize the CPU resources and handle multi simultaneous task.

Channel provides a way to communicate / sync between isolated thread.

It can help to prevent race conditions and make concurrent programming more manageable and comprehensible.

$(document).ready(function () {
  var $btn = $("#btn"),
    $list = $("#list"),
    clicks = ASQ.csp.chan(),
    msgs = ASQ.csp.chan(),
    queuedClick;

  $btn.click(listenToClicks);

  // run go-routines
  ASQ().runner(ASQ.csp.go(sampleClicks), ASQ.csp.go(logClick));

  // push click event messages into channel
  function listenToClicks(evt) {
    if (!queuedClick) {
      // putAsync will handle event in sequence
      queuedClick = ASQ.csp.putAsync(clicks, evt);
      queuedClick.then(function () {
        queuedClick = null;
      });
    }
  }

  // sample clicks channel
  function* sampleClicks() {
    while (true) {
      yield ASQ.csp.take(ASQ.csp.timeout(1000));
      yield ASQ.csp.take(clicks);
      yield ASQ.csp.put(msgs, "clicked!");
    }
  }

  // subscribe to sampled message channel
  function* logClick() {
    while (true) {
      var msg = yield ASQ.csp.take(msgs);
      $list.append($("<div>" + msg + "</div>"));
    }
  }
});

 

Reactive programming:

It is suitable for event-driven, and asynchronous data streams. It is a declarative approach to handle async streams of data.

It has operators which you can compose different operators to perform complex logic and results in a maintable and readable codebase.

 

Main difference between CSP and reactive programming, IMO, it is CSP automaticlly handle backpressure, but for Reactive programming, you need to use operators doing `buffering, dropping, throttling, blocking` operation for you.

posted @ 2023-10-31 15:10  Zhentiw  阅读(2)  评论(0编辑  收藏  举报