Search code examples
pythonreactive-programmingrx-py

How to use Reactive Extensions (Rx) LINQ in Python?


I downloaded RxPY and was watching the Rx tutorials when I came across:

enter image description here

So how would I get the above working in Python with RxPY? In particular, the query q = from x in xs where... is not syntactically valid Python code -- so how would this be changed?


Solution

  • All LINQ queries in C# could be easily converted to a extension methods (where is for Where, and select is for Select):

    In [20]: from rx import Observable
    
    In [21]: xs = Observable.range(1, 10)
    
    In [22]: q = xs.where(lambda x: x % 2 == 0).select(lambda x: -x)
    
    In [23]: q.subscribe(print)
    -2
    -4
    -6
    -8
    -10
    

    You may also use filter instead of where and map instead of select:

    In [24]: q = xs.filter(lambda x: x % 2 == 0).map(lambda x: -x)
    
    In [25]: q.subscribe(print)
    -2
    -4
    -6
    -8
    -10