forked from yanyunchangfeng/learn-rxjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
127 lines (112 loc) · 2.41 KB
/
index.ts
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
console.log('Hello World')
const callback = ()=>{
console.log('Hello World')
}
const reminder =()=>{
console.log('Time to drink water!')
}
const reminderCb = (cb:any)=>{
cb()
}
const reminderCbAndTimerCb = (cb:any)=>{
cb()
setTimeout(() => {
cb()
}, 1000)
}
reminder()
reminderCb(()=>{console.log('Time to write code !')})
reminderCbAndTimerCb(()=>{console.log('Time to wtire code again and again')})
class Reminder {
remind(cb:any){
cb.next(1);
cb.complete()
}
}
const reminder1 = new Reminder();
reminder1.remind({
next:(val:any)=>{
console.log(val,'next')
},
complete:(val:any)=>{
console.log(val)
},
})
class Reminder2 {
behavior:any;
constructor(behavior:any){
this.behavior = behavior
}
remind(cb:any){
this.behavior(cb)
}
}
const reminder2 = new Reminder2((cb:any )=>{
cb.next(2);
cb.complete();
})
reminder2.remind({
next(val:any){
console.log(val,'next2')
},
complete(val:any){
console.log(val,'complete')
},
})
// Reminder => Observable
// remind => subscribe
// cb => observer
// reminder => obs$
class Observable {
behavior:any; // 或者_subscribe
constructor(behavior:any){
this.behavior = behavior
// this._subscribe = subscribe 构造函数也可用subscribe
}
subscribe(observer:any){
this.behavior(observer)
// this._subscribe(observer)
}
}
const obs$ = new Observable((observer:any)=>{
observer.next(1);
throw new Error(" ddd");
observer.complete()
})
const observer = {
next:(val:any) =>{
console.log(val,'observer next')
},
error:(err:any)=>{
console.log(err,'err')
},
complete:()=>{
console.log('complete')
}
}
obs$.subscribe(observer)
// 官方 Observable 的 subscribe 可以传入一个函数进去,这样的话写起来会清爽很多,我们也来实现一下
class OfficialObservable {
_subscribe:any; // 或者_subscribe
constructor(subscribe:any){
this._subscribe = subscribe
// this._subscribe = subscribe 构造函数也可用subscribe
}
subscribe(observer:any):any{
const defaultObserver = {
next:()=>{
console.log('next')
},
err:()=>{
console.log('err')
},
complete:()=>{
console.log('complete')
}
}
if(typeof observer === 'function'){
return this.subscribe({...defaultObserver,next:observer})
}
return this._subscribe({...defaultObserver,...observer})
}
}