Thursday, 4 February 2021

Python reactive programming conditional executions

I started learning about reactive programming in Python using the RxPy module. Now, I have a case where I would like to run different functions depending on the received elements. I've achieved it in a very straightforward approach

from rx.subject import Subject
from rx import operators as ops

def do_one():
    print('exec one')

def do_two():
    print('exec two')

subject = Subject()
subject.pipe(
    ops.filter(lambda action: action == 'one')
).subscribe(lambda x: do_one())

subject.pipe(
    ops.filter(lambda action: action == 'two')
).subscribe(lambda x: do_two())


subject.on_next('one')
subject.on_next('two')

To me this seems a bit ugly, however, I couldn't quite find any case, switch or other method in operations/Observables to trigger the different executions depending on the element received.

Is there a better way of doing this?



from Python reactive programming conditional executions

No comments:

Post a Comment