From d7d41b878c19dd2958c1b1e5b810de49e5c15fe5 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Sat, 15 Apr 2023 19:21:11 +0200 Subject: [PATCH] Added behavior subject --- .../behavior_subject.py | 23 +++++++++++++++++++ src/cpl_reactive_extensions/subject.py | 11 --------- .../reactive_test_case.py | 12 ++++++++++ 3 files changed, 35 insertions(+), 11 deletions(-) create mode 100644 src/cpl_reactive_extensions/behavior_subject.py diff --git a/src/cpl_reactive_extensions/behavior_subject.py b/src/cpl_reactive_extensions/behavior_subject.py new file mode 100644 index 00000000..18b087c0 --- /dev/null +++ b/src/cpl_reactive_extensions/behavior_subject.py @@ -0,0 +1,23 @@ +from cpl_core.type import T +from cpl_reactive_extensions.observable import Observable + + +class BehaviorSubject(Observable): + def __init__(self, _t: type, value: T): + Observable.__init__(self, lambda x: x) + + if not isinstance(value, _t): + raise TypeError(f"Expected {_t.__name__} not {type(value).__name__}") + + self._t = _t + self._value = value + + @property + def value(self) -> T: + return self._value + + def next(self, value: T): + if not isinstance(value, self._t): + raise TypeError(f"Expected {self._t.__name__} not {type(value).__name__}") + + self._value = value diff --git a/src/cpl_reactive_extensions/subject.py b/src/cpl_reactive_extensions/subject.py index 0b0e25bb..864ea2b2 100644 --- a/src/cpl_reactive_extensions/subject.py +++ b/src/cpl_reactive_extensions/subject.py @@ -7,14 +7,3 @@ class Subject(Observable): Observable.__init__(self) self._t = _t - self._value: T = None - - @property - def value(self) -> T: - return self._value - - def next(self, value: T): - if not isinstance(value, self._t): - raise TypeError(f"Expected {self._t.__name__} not {type(value).__name__}") - - self._value = value diff --git a/unittests/unittests_reactive_extenstions/reactive_test_case.py b/unittests/unittests_reactive_extenstions/reactive_test_case.py index 7b590394..96a28979 100644 --- a/unittests/unittests_reactive_extenstions/reactive_test_case.py +++ b/unittests/unittests_reactive_extenstions/reactive_test_case.py @@ -4,6 +4,7 @@ import unittest from threading import Timer from cpl_core.console import Console +from cpl_reactive_extensions.behavior_subject import BehaviorSubject from cpl_reactive_extensions.observable import Observable from cpl_reactive_extensions.observer import Observer from cpl_reactive_extensions.subject import Subject @@ -114,3 +115,14 @@ class ReactiveTestCase(unittest.TestCase): observable.subscribe(subject, self._on_error) self.assertFalse(self._error) + + def test_behavior_subject(self): + subject = BehaviorSubject(int, 0) + + subject.subscribe(lambda x: Console.write_line("a", x)) + + subject.next(1) + subject.next(2) + + subject.subscribe(lambda x: Console.write_line("b", x)) + subject.next(3)