Skip to main content

Observables

The @devicescript/observables builtin package provides a lightweight reactive observable framework, a limited subset of RxJS. We highly recommend reviewing the RxJS documentation for deeper discussions about observables.

Motivation

Imagine a temperature sensor, it routinely senses the temperature and updates the temperature register. The temperature register is an observable of sensor reading.

If you write code in DeviceScript to listen for this data, it will look like this:

import { Temperature } from "@devicescript/clients"

const thermometer = new Temperature()
const { temperature } = thermometer
temperature.subscribe(temp => console.log(temp))

In particular, the handler passed to subscribe will be called whenever a new temperature reading is received (even if it did not change). The program would print something like this:

20
21
21
20

A better way to visualize streams of data and how observable handle them is to use a marble diagram. The input stream (on top) arrives unchanged to the subscribe handler and is printed to the console.

output.svg

As you can see, there are 2 data readings with the same temperature and we would like to filter them out. Using the threshold operator, which filters out small data changes, we get

import { Temperature } from "@devicescript/clients"
import { threshold } from "@devicescript/observables"

const thermometer = new Temperature()
const { temperature } = thermometer
temperature
.pipe(threshold(1))
.subscribe(temp => console.log(temp))
output.svg

Operators can be chained and combined to create complex data processing pipelines. Custom operators can also be defining by combining existing ones or writing them from bare code.

See also