Star

Created With


subscribe



Greets the given source, and starts listening to its values.

1linkfunction subscribe<T>(listener: (data: T) => void): () => void

1linkimport { interval, map, subscribe, pipe } from 'callbag-common';

2link

3linkconst src = pipe(

4link interval(1000),

5link map(x => x * 3)

6link);

7link

8linksubscribe(console.log)(src);

You can call subscribe() at the end of a pipe chain too:

1linkimport { interval, map, subscribe, pipe } from 'callbag-common';

2link

3linkpipe(

4link interval(1000),

5link map(x => x * 3),

6link subscribe(console.log)

7link);


👉 Before calling subscribe(), the source is not greeted and it might not do anything at all. For example, interval() will not start its timer before being greeted (and it will start a new timer for every new greeter).

👉 subscribe() returns a method that you can call to end the subscription (i.e. send an end signal to the source). This is important as if you don't clean up, resources (like memory) might not get released properly:

1linkimport { interval, map, subscribe, pipe } from 'callbag-common';

2link

3linkconst src = pipe(

4link interval(1000),

5link map(x => x * 3)

6link);

7link

8linkconst cleanup = subscribe(console.log)(src);

9link

10linksetTimeout(() => cleanup(), 5000);

Or using pipe:

1link​import { interval, map, subscribe, pipe } from 'callbag-common';

2link​

3link​const cleanup = pipe(

4link​ interval(1000),

5link​ map(x => x * 3),

6link​ subscribe(console.log)

7link​);

8link​

9link​setTimeout(() => cleanup(), 5000);

10link​

0 3 6 9
â–º Try It!



Home What Are Callbags?

Source Factorieschevron_right
Operatorschevron_right
Combinationchevron_right
Utilitieschevron_right