portfolio/packages/frptools/docs/subscribable.md

994 B

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:

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.