Skip to content

Commit

Permalink
Allow using observables for sensors
Browse files Browse the repository at this point in the history
This is useful for creating agent sensors on some data coming from a
stream values

Change-type: minor
  • Loading branch information
pipex committed May 3, 2024
1 parent 9387bdc commit 3c505e3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
20 changes: 20 additions & 0 deletions lib/sensor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Sensor } from './sensor';
import { Ref } from './ref';
import { stub } from 'sinon';
import { setTimeout } from 'timers/promises';
import { Observable } from './observable';

describe('Sensor', () => {
it('only starts execution once subscribers have been added', async () => {
Expand Down Expand Up @@ -53,6 +54,25 @@ describe('Sensor', () => {
expect(state._.temperature).to.equal(23);
});

it('allows reporting on a value using observable', async () => {
type Heater = { temperature: number; on: boolean };
const sensor = Sensor.of<Heater>().from({
lens: '/temperature',
sensor: () => Observable.from([20, 23]),
});

const state = Ref.of({ temperature: 0, on: false });

const next = stub();
sensor(state).subscribe(next);

await setTimeout(10);

expect(next).to.have.been.calledWith({ temperature: 20, on: false });
expect(next).to.have.been.calledWith({ temperature: 23, on: false });
expect(state._.temperature).to.equal(23);
});

it('allows reporting on a value using lenses with args', async () => {
type Heater = { temperature: { [room: string]: number }; on: boolean };
const sensor = Sensor.of<Heater>().from({
Expand Down
3 changes: 2 additions & 1 deletion lib/sensor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export type SensorFn<T, P extends PathType = '/'> = (
args: LensArgs<T, P>,
) =>
| AsyncGenerator<Lens<T, P>, never | void | Lens<T, P>, void>
| Generator<Lens<T, P>, never | void, void | undefined>;
| Generator<Lens<T, P>, never | void, void | undefined>
| Subscribable<Lens<T, P>>;

/**
* A sensor receives a reference to a global state and
Expand Down

0 comments on commit 3c505e3

Please sign in to comment.