Twisted: deferred that fires repeatedly?

2019-02-07 06:48发布

Deferreds 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?

2条回答
Rolldiameter
2楼-- · 2019-02-07 07:26

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.

查看更多
冷血范
3楼-- · 2019-02-07 07:26

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.

查看更多
登录 后发表回答