Deferred
s are a great way to do asynchronous processing in Twisted. However, they, like the name implies, are for deferred computations, which only run and terminate once, firing the callbacks once. What if I have a repeated computation, like a button being clicked? Is there any Deferred
-like object that can fire repeatedly, calling all callbacks attached to it whenever it is fired?
views:
60answers:
2
+1
A:
I've set this up for now. For my limited use case it does what I want.
class RepeatedDeferred:
def __init__(self):
self.callbacks = []
self.df = defer.Deferred()
def addCallback(self, callback):
self.callbacks.append(callback)
self.df.addCallback(callback)
def callback(self, res):
self.df.callback(res)
self.df = defer.Deferred()
for c in self.callbacks:
self.df.addCallback(c)
Someone let me know if this is terrible.
Claudiu
2010-08-18 20:04:49
A:
What you might be looking for is defer.inlineCallbacks
which allows you to use a generator to create a sequential chain of Deferreds. Essentially you could just create a generator that never ends (or ends conditionally) and keep generating Deferreds from that.
There is a great writeup on using inlineCallbacks
at krondo.com.
jathanism
2010-08-18 23:48:35
heh awesome feature. reminds me of monads in Haskell, kinda. i don't think it's what I'm looking for, though. i'll think about it more when its not so late
Claudiu
2010-08-19 03:28:31