43 lines
1.5 KiB
Markdown
43 lines
1.5 KiB
Markdown
# stream
|
|
|
|
A `stream` is a [computed](./computed.md) that works asynchronously. Dependencies can be synchronous
|
|
or asynchronous functions returning a scalar or a promise respectively. Also calling a stream
|
|
multiple overlapping times will return the same promise and result (so long as dependencies do not
|
|
change in the time gap). In this way, stream can serve as a temporal deduplicator.
|
|
|
|
## Usage
|
|
|
|
### Creation
|
|
|
|
```js
|
|
const getToken = stream(
|
|
async tokenUrl => fetch(tokenUrl), // computation function
|
|
[getTokenUrl, tokenTimeout] // array of subscribable dependencies
|
|
);
|
|
```
|
|
|
|
Note: Property and container dependencies are "locked" while the computation function is run. If
|
|
there are any out-of-band updates to a dependency, the value will be set but will not propagate
|
|
until after the computation function is complete and the stream's subscribers are notified.
|
|
|
|
### Read
|
|
|
|
```js
|
|
if (await getToken()) {
|
|
/* do stuff with the token */
|
|
}
|
|
```
|
|
|
|
### Provide a hash function for complex result types
|
|
|
|
When the stream result is a type that is not determined to be equal with simple equality (===),
|
|
provide a hash function to the `hashableStream` type to create a stream that will reduce the result
|
|
value to a value that can be compared with the identity operator before comparison. The computed
|
|
result value will still be stored unmodified.
|
|
|
|
```js
|
|
const tokenStream = hashableStream(token => token && token.id);
|
|
|
|
const getToken = tokenStream(async tokenUrl => fetch(tokenUrl), [getTokenUrl]);
|
|
```
|