-
Notifications
You must be signed in to change notification settings - Fork 364
/
Copy pathnotification.py
205 lines (152 loc) · 6.15 KB
/
notification.py
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
from abc import abstractmethod
from typing import Any, Callable, Generic, Optional, TypeVar, Union
from reactivex import abc, typing
from reactivex.scheduler import ImmediateScheduler
from .observable import Observable
from .observer import Observer
_T = TypeVar("_T")
class Notification(Generic[_T]):
"""Represents a notification to an observer."""
def __init__(self) -> None:
"""Default constructor used by derived types."""
self.has_value = False
self.value: _T
self.kind: str = ""
def accept(
self,
on_next: Union[typing.OnNext[_T], abc.ObserverBase[_T]],
on_error: Optional[typing.OnError] = None,
on_completed: Optional[typing.OnCompleted] = None,
) -> None:
"""Invokes the delegate corresponding to the notification or an
observer and returns the produced result.
Examples:
>>> notification.accept(observer)
>>> notification.accept(on_next, on_error, on_completed)
Args:
on_next: Delegate to invoke for an OnNext notification.
on_error: [Optional] Delegate to invoke for an OnError
notification.
on_completed: [Optional] Delegate to invoke for an
OnCompleted notification.
Returns:
Result produced by the observation."""
if isinstance(on_next, abc.ObserverBase):
return self._accept_observer(on_next)
return self._accept(on_next, on_error, on_completed)
@abstractmethod
def _accept(
self,
on_next: typing.OnNext[_T],
on_error: Optional[typing.OnError],
on_completed: Optional[typing.OnCompleted],
) -> None:
raise NotImplementedError
@abstractmethod
def _accept_observer(self, observer: abc.ObserverBase[_T]) -> None:
raise NotImplementedError
def to_observable(
self, scheduler: Optional[abc.SchedulerBase] = None
) -> abc.ObservableBase[_T]:
"""Returns an observable sequence with a single notification,
using the specified scheduler, else the immediate scheduler.
Args:
scheduler: [Optional] Scheduler to send out the
notification calls on.
Returns:
An observable sequence that surfaces the behavior of the
notification upon subscription.
"""
_scheduler = scheduler or ImmediateScheduler.singleton()
def subscribe(
observer: abc.ObserverBase[_T],
scheduler: Optional[abc.SchedulerBase] = None,
) -> abc.DisposableBase:
def action(scheduler: abc.SchedulerBase, state: Any) -> None:
self._accept_observer(observer)
if self.kind == "N":
observer.on_completed()
__scheduler = scheduler or _scheduler
return __scheduler.schedule(action)
return Observable(subscribe)
def equals(self, other: "Notification[_T]") -> bool:
"""Indicates whether this instance and a specified object are
equal."""
other_string = "" if not other else str(other)
return str(self) == other_string
def __eq__(self, other: Any) -> bool:
return self.equals(other)
class OnNext(Notification[_T]):
"""Represents an OnNext notification to an observer."""
def __init__(self, value: _T) -> None:
"""Constructs a notification of a new value."""
super(OnNext, self).__init__()
self.value: _T = value
self.has_value: bool = True
self.kind: str = "N"
def _accept(
self,
on_next: typing.OnNext[_T],
on_error: Optional[typing.OnError] = None,
on_completed: Optional[typing.OnCompleted] = None,
) -> None:
return on_next(self.value)
def _accept_observer(self, observer: abc.ObserverBase[_T]) -> None:
return observer.on_next(self.value)
def __str__(self) -> str:
val: Any = self.value
if isinstance(val, int):
val = float(val)
return "OnNext(%s)" % str(val)
class OnError(Notification[_T]):
"""Represents an OnError notification to an observer."""
def __init__(self, error: Union[Exception, str]) -> None:
"""Constructs a notification of an exception."""
super(OnError, self).__init__()
self.exception: Exception = (
error if isinstance(error, Exception) else Exception(error)
)
self.kind = "E"
def _accept(
self,
on_next: typing.OnNext[_T],
on_error: Optional[typing.OnError],
on_completed: Optional[typing.OnCompleted],
) -> None:
return on_error(self.exception) if on_error else None
def _accept_observer(self, observer: abc.ObserverBase[_T]) -> None:
return observer.on_error(self.exception)
def __str__(self) -> str:
return "OnError(%s)" % str(self.exception)
class OnCompleted(Notification[_T]):
"""Represents an OnCompleted notification to an observer."""
def __init__(self) -> None:
"""Constructs a notification of the end of a sequence."""
super(OnCompleted, self).__init__()
self.kind = "C"
def _accept(
self,
on_next: typing.OnNext[_T],
on_error: Optional[typing.OnError],
on_completed: Optional[typing.OnCompleted],
) -> None:
return on_completed() if on_completed else None
def _accept_observer(self, observer: abc.ObserverBase[_T]) -> None:
return observer.on_completed()
def __str__(self) -> str:
return "OnCompleted()"
def from_notifier(handler: Callable[[Notification[_T]], None]) -> Observer[_T]:
"""Creates an observer from a notification callback.
Args:
handler: Action that handles a notification.
Returns:
The observer object that invokes the specified handler using
a notification corresponding to each message it receives.
"""
def _on_next(value: _T) -> None:
return handler(OnNext(value))
def _on_error(error: Exception) -> None:
return handler(OnError(error))
def _on_completed() -> None:
return handler(OnCompleted())
return Observer(_on_next, _on_error, _on_completed)