merge repeated subscription events

This commit is contained in:
Victor Shyba 2019-08-07 02:48:40 -03:00
parent 822f53c888
commit d1f5b25418
3 changed files with 27 additions and 4 deletions

View file

@ -0,0 +1,19 @@
import unittest
from torba.stream import StreamController
class StreamControllerTestCase(unittest.TestCase):
def test_non_unique_events(self):
events = []
controller = StreamController()
controller.stream.listen(on_data=events.append)
controller.add("yo")
controller.add("yo")
self.assertEqual(events, ["yo", "yo"])
def test_unique_events(self):
events = []
controller = StreamController(merge_repeated_events=True)
controller.stream.listen(on_data=events.append)
controller.add("yo")
controller.add("yo")
self.assertEqual(events, ["yo"])

View file

@ -89,10 +89,10 @@ class BaseNetwork:
self._on_connected_controller = StreamController() self._on_connected_controller = StreamController()
self.on_connected = self._on_connected_controller.stream self.on_connected = self._on_connected_controller.stream
self._on_header_controller = StreamController() self._on_header_controller = StreamController(merge_repeated_events=True)
self.on_header = self._on_header_controller.stream self.on_header = self._on_header_controller.stream
self._on_status_controller = StreamController() self._on_status_controller = StreamController(merge_repeated_events=True)
self.on_status = self._on_status_controller.stream self.on_status = self._on_status_controller.stream
self.subscription_controllers = { self.subscription_controllers = {

View file

@ -45,10 +45,12 @@ class BroadcastSubscription:
class StreamController: class StreamController:
def __init__(self): def __init__(self, merge_repeated_events=False):
self.stream = Stream(self) self.stream = Stream(self)
self._first_subscription = None self._first_subscription = None
self._last_subscription = None self._last_subscription = None
self._last_event = None
self._merge_repeated = merge_repeated_events
@property @property
def has_listener(self): def has_listener(self):
@ -76,8 +78,10 @@ class StreamController:
return f return f
def add(self, event): def add(self, event):
skip = self._merge_repeated and event == self._last_event
self._last_event = event
return self._notify_and_ensure_future( return self._notify_and_ensure_future(
lambda subscription: subscription._add(event) lambda subscription: None if skip else subscription._add(event)
) )
def add_error(self, exception): def add_error(self, exception):