Skip to content

listen ​

Registers a function that will be called whenever something in Observable changes.

Syntax ​

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

listen(observable, listener);

Arguments ​

  • observable – Any Observable object created by extends Observable or makeObservable.
  • listener – A function that will be called whenever something in Observable object changes. It will be called with two arguments:
    • key – Property name in target Observable which were changed.
    • value – New value attached to this property.

Return value ​

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

example ​

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

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

const dispose = listen(state, (key, value) => {
  console.log(changes);
});

state.mutate(); 
// a, 2; 
// c, [1]; 
// b, false;
dispose();

state.mutate(); //

WARNING

Avoid mutating state inside listener, as it will lead to infinite loop and stack overflow error.

kroman@observable.ru