This module supports event sources, listeners, subscriptions, generator-based pseudothreads ("tasks"), scheduling, and I/O events. Using 'peak.events', you can write event-driven code in a more natural, sequential, "untwisted" style, but without giving up access to Twisted's many great features. 'peak.events' can use PEAK's built-in event loop, or adapt a Twisted reactor for use as an event loop. You can also use Twisted's "Deferred" objects as event sources, which means you can use them in your Tasks (pseudothreads).
To use PEAK's event system it's pretty straightforward. You create an event source, you subscribe to its event and then wait for the event to be triggered. The event source we are going to use is called Broadcaster, we'll talk about it more a bit further.
1 from peak.events.api import * 2 3 source = Broadcaster () 4 5 def callback (source, event): 6 print "Helo world!" 7 8 9 canceller = subscribe (source, callback) 10 11 source.send (None)
The canceller object is a reference to our subscription, once the reference is lost our subscription is lost too. We can cancel our subscription explicitly by calling the canceller object.
The output would be:
Two event sources are called Distributor and Broadcaster. An event source is what you have to subscribe to listen for the events they send.
The difference between Distributor and a Broadcaster is a very simple one. You may assign more then one listener (or callback) to an event source. When the event source generates a given event, it will iterate over its listeners in the order in which they were subscribed and send the event to each one. In the case of a Distributer, when one of its listeners returns True, the iteration stops.
1 from peak.events.api import * 2 3 source_dist = Distributor () 4 source_bcst = Broadcaster () 5 6 def callback1 (source, event): 7 print "Hello from callback1" 8 return True 9 10 def callback2 (source, event): 11 print "hello from callback2" 12 13 c1 = subscribe (source_dist, callback1) 14 c2 = subscribe (source_dist, callback2) 15 16 c3 = subscribe (source_bcst, callback1) 17 c4 = subscribe (source_bcst, callback2) 18 19 source_dist.send (None) 20 source_bcst.send (Nine)
The output of this snippet is going to be:
Hello from callback1 Hello from callback1 Hello from callback2