-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.clj
71 lines (48 loc) · 1.6 KB
/
stream.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
(ns hello-world.stream
(:require [re-streamer.stream :as stream]))
;; create stream
(def bar (stream/create))
;; subscribe to the stream
(def sub1 ((:subscribe! bar) #(println (:message %))))
;; emit new value
((:emit! bar) {:message "World"})
;; output:
;; World
;; emit new value
((:emit! bar) {:message "Developers"})
;; output:
;; Developers
;; add one more subscription
(def sub2 ((:subscribe! bar) #(println (str "Hello " (:message %)))))
;; emit new value
((:emit! bar) {:message "Clojure Developers"})
;; output:
;; Clojure Developers (first subscription)
;; Hello Clojure Developers (second subscription)
; remove second subscription
((:unsubscribe! bar) sub2)
;; emit new value
((:emit! bar) {:message "Functional Programming"})
;; output:
;; Functional Programming (first subscription)
;; in the end, remove first subscription in order to reduce memory leaks
((:unsubscribe! bar) sub1)
;; to remove all subscriptions use flush function
(def sub3 ((:subscribe! bar) #(println (str (:message %) " Really"))))
(def sub4 ((:subscribe! bar) #(println (str (:message %) " in Clojure(Script)"))))
((:emit! bar) {:message "Re-Streamer Rocks"})
;; output:
;; Re-Streamer Rocks Really (sub3)
;; Re-Streamer Rocks in Clojure(Script) (sub4)
;; let's now flush the stream
((:flush! bar))
((:emit! bar) {:message "Reactive Programming"})
;; output:
;; (there are no printed values, because there are no subscriptions)
;; so, if you want to remove all subscriptions,
;; use flush instead of calling unsubscribe many times
;; first way
((:unsubscribe! bar) sub3)
((:unsubscribe! bar) sub4)
;; second way
((:flush! bar))