This repository has been archived on 2020-09-01. You can view files and clone it, but cannot push or open issues or pull requests.
reactimal/docs/subscribable.md

34 lines
994 B
Markdown

# Subscribable
A subscribable is a common interface for all of the primitives provided by this library.
Each subscribable has the following methods:
## subscribe(callback)
`subscribe` takes a _callback_ function that will be called when the primitive's value changes.
`subscribe` will return an _unsubscribe_ function that will unsubscribe the _callback_ from the
primitive when called. The returned _unsubscribe_ function will also return the remaining number of
subscriptions for that primitive.
Example:
```js
const p = prop(false);
const unsubscribe = p.subscribe(val => console.log(val));
p(true); // Logs "true" to the console
p(true); // Nothing logged because the value of p did not change.
const remainingSubscriptionCount = unsubscribe();
p(false); // Nothing logged because the subscription was revoked.
if (remainingSubscriptionCount === 0) {
// Run any necessary cleanup
}
```
## unsubscribeAll()
`unsubscribeAll` simply disconnects all subscribers from the primitive.