3

I'm looking for a very basic example of how to use reactive extensions (RxPY) and Twisted. Here's a minimal hello application that uses Twisted to stream messages.

def hello():
    print 'Hello from the reactor loop!'
    print 'Lately I feel like I\'m stuck in a rut.'

from twisted.internet import reactor

reactor.callWhenRunning(hello)

print 'Starting the reactor.'
reactor.run()

I'd like to use the RxPY library to hook into these streams (they don't have to print out to the screen if that makes it easier), and do canonical operations like map, filter etc...

All of the examples of RxPY I can find either generate their own streams, for example from an iterable, the following code streams integers 0-9:

xs = Observable.from_(range(10))
xs.map(
    lambda x: x * 2
      ).subscribe(print)

Or are included in more complex example (like subclassing WebSocket Handler). Any idea how I can intercept the print messages? EG, generate a stream of observables from the Twisted reactor?

Yaroslav Stavnichiy
  • 20,738
  • 6
  • 52
  • 55
Adam Hughes
  • 14,601
  • 12
  • 83
  • 122

1 Answers1

3

I've been trying to figure out the same thing. Here are my findings.

The easiest way to initiate RX data stream is to create Subject() which combines both Observer and Observable. Then you can feed your data into it using on_next method.

The Rx part:

from rx.subjects import Subject
subject=Subject()
subject.filter(...).map(...).subscribe(my_observer)

And from your twisted callback you simply do:

subject.on_next(data_item)
...
subject.on_completed()

or you can signal an error:

subject.on_error(my_error)

While learning RxPy I've written simple web server using both RxPy and Twisted. It is single python file, which can be used as an example.

Yaroslav Stavnichiy
  • 20,738
  • 6
  • 52
  • 55