Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Latest" pattern #76

Open
buchanae opened this issue Nov 29, 2015 · 1 comment
Open

"Latest" pattern #76

buchanae opened this issue Nov 29, 2015 · 1 comment

Comments

@buchanae
Copy link

Let's say I have a source channel which contains the result of an expensive operation. I have a reader that reads from this source channel every 1 second. I want to read from the source, but only read the latest (or cached) value.

I think there a couple ways to do this:

With a custom buffer

var LatestBuffer = function(buf) {
  this.buf = buf;
};

LatestBuffer.prototype.is_full = function() {
  return false;
};

LatestBuffer.prototype.remove = function() {
  return this.buf;
};

LatestBuffer.prototype.add = function(item) {
  this.buf = item;
};

LatestBuffer.prototype.count = function() {
  return 1;
};

var channel = csp.chan(new LatestBuffer());
csp.operations.pipe(sourceCh, channel);

With a couple goroutines

var latest;

csp.go(function*() {
   while (true) {
    latest = yield sourceCh;
  }
});

var channel = csp.go(function*() {
  while (true) {
    yield latest;
  }
});

Is one better than the other? I think I like LatestBuffer more. Is there a better way? Would this be nice to have in js-csp?

Thanks!

@laurentsenta
Copy link

Thanks for sharing, I needed this to expose the current payload of a system of channels / streams.

The 2017 version, with flow + es6, jest tests below

export class LatestBuffer<T> {
  item: T

  constructor(item: T) {
    this.item = item
  }

  isFull(): boolean {
    return false
  }

  count(): number {
    return 1
  }

  remove(): T {
    return this.item
  }

  add(item: T): void {
    this.item = item
  }
}
test('The LatestBuffer can be used to store the last value that went through the channel', () => goPromise(function*() {
  // Arrange
  const c = chan(new LatestBuffer())

  // Act
  const v1 = yield take(c)
  yield put(c, 12)
  const v2 = yield take(c)
  const v3 = yield take(c)
  yield put(c, 24)
  const v4 = yield take(c)

  // Assert
  expect(v1).toBeUndefined()
  expect(v2).toBe(12)
  expect(v3).toBe(12)
  expect(v4).toBe(24)
}))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants