Skip to content

subscribe ​

Registers a function, that will be called whenever certain properties changes.

Syntax ​

ts
import { subscribe } from 'kr-observable';

subscribe(observable, subscriber, properties);

Arguments ​

  • observable – Any Observable object created by extends Observable or makeObservable.
  • subscriber – A function that will be called whenever certain properties changes. It will be called with one argument:
    • keys – A Set of strings that represents properties in the target Observable that have been changed. It may contain one or more properties, if changes were made almost at the same time.
  • properties – A Set of strings that represents properties in target Observable you want to observe. The subscriber will be called only when one or more of these properties will change.

    TIP

    If you save a reference to the properties, you can add or remove properties at run time. subscriber will be called only for those properties that are currently in Set.

Return value ​

A disposer function that, when called, stops tracking observable and unsubscribe from it.

Example ​

ts
import { subscribe, makeObservable } from 'kr-observable';

const state = makeObservable({
  a: 1,
  b: true,
  c: [],
  
  mutate() {
    this.a += 1;
    this.c.push(1);
  }
})

const dispose = subscribe(state, (changes) => {
  console.log(changes);
}, new Set(['a', 'c']));

state.mutate(); // Set(a, c)

dispose();

state.mutate(); //

kroman@observable.ru