34 lines
994 B
Markdown
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.
|