Switch

Definition

class broqer.op.Switch(mapping: Dict[Any, Any], default: Any = <class 'broqer.types.NONE'>, subscribe_all=False)[source]

Forwards emits from a selected publisher (mapped by mapping).

Parameters:
  • mapping – dictionary with value:(Publisher|constant) mapping
  • default – value emitted if key is not found
  • subscribe_all – if True all publishers are subscribed on operator subscription. Otherwise only the selected publisher will be subscribed.

Usage

Emit a publisher mapped by mapping

Usage:

>>> from broqer import Subject, Value, op
>>> choose = Subject()
>>> s1 = Value(0)
>>> s2 = Subject()
>>> switch_publisher = choose | op.Switch({'a':s1, 'b':s2})
>>> _d = switch_publisher | op.Sink(print)
>>> s1.emit(1)
>>> s2.emit(2)
>>> choose.emit('b')
>>> s1.emit(1)
>>> s2.emit(2)
2
>>> choose.emit('a')
1
>>> _d.dispose()

Also using switch as if-then-else construct is possible. This is working because False is correpsonding to integer 0, True is 1

>>> if_publisher = choose | op.Switch([s1, s2])
>>> _d = if_publisher | op.Sink(print)
>>> s1.emit(1)
>>> s2.emit(2)
>>> choose.emit(True)
>>> s1.emit(1)
>>> s2.emit(2)
2
>>> choose.emit(False)
1