Action Consolidator

There are a class of idempotent asynchronous actions that will typically return the same results when called in a rapid succession. This class of async operations can easily and rather safely be consolidated such that if we have multiple operations requesting the same peice of data or the same action be ran we only need to run it once and share the results with all the interested parties.

This library provides a simple API as a means to facilitate this run once share many approach to async operations. Providing a step in the right direction to solving some "thundering horde" problems and just effeciently using resources.

Example

import 'dart:async';
import 'package:action_consolidator/action_consolidator.dart';

main() {

  // Create the action consolidator
  var consolidator = new ActionConsolidator<String>();

  // S simple mock async action which would behave like a memcache get
  var asyncAction = (String key) {
    return () {
      print('** Running the async mock memcache call for ${key}');
      return new Future.delayed(new Duration(seconds:2), () => "** Got ${key}");
    };
  };

  // Call `asyncAction` 3 times via the consolidator, it should only
  // get ran once, but should return 3 times
  var future1 = consolidator.run("user:joe", asyncAction("user:joe"));
  var future2 = consolidator.run("user:joe", asyncAction("user:joe"));
  var future3 = consolidator.run("user:joe", asyncAction("user:joe"));
  future1.then(print);
  future2.then(print);
  future3.then(print);

  // Call interweaved actions, they should queue properly
  var future4 = consolidator.run("user:moe", asyncAction("user:moe"));
  var future5 = consolidator.run("user:bob", asyncAction("user:bob"));
  var future6 = consolidator.run("user:moe", asyncAction("user:moe"));
  var future7 = consolidator.run("user:bob", asyncAction("user:bob"));
  future4.then(print);
  future5.then(print);
  future6.then(print);
  future7.then(print);
}

Public Interface

library action_consolidator;

import 'dart:async';

class ActionConsolidator<V> {

  /**
   * Typical constructor
   */
  ActionConsolidator();

  /**
   * The asyncronous action consolidator and deduplicator
   *
   * @param {String} key       - The key to consolidate on
   * @param {Future<V>} action - The async action to consolidate
   * @return {Future<V>}       - The completion future
   */
  Future<V> run(String key, Future<V> action());

}

Libraries

action_consolidator