Skip to Content
Hands-On Reactive Programming with Python
book

Hands-On Reactive Programming with Python

by Romain Picard
October 2018
Intermediate to advanced
420 pages
10h 26m
English
Packt Publishing
Content preview from Hands-On Reactive Programming with Python

Using generators for asynchronous handlers

So how can generators help with writing asynchronous code? The twist comes from the fact that a generator can be interrupted where we want it to be and resumed later when something happens, such as when an asynchronous action is completed. This means that generators can be used to trigger asynchronous action executions with the yield expression, and they can be resumed when the action has completed.

Let's rewrite the state machine as a generator. The asynchronous operations are the read calls on the transport channel. So, each time the state machine needs to get some data, it has to yield so that more data can be read. Here is the new code of the state machine:

def parser(read_next): while True: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python Programming with Design Patterns

Python Programming with Design Patterns

James W. Cooper

Publisher Resources

ISBN: 9781789138726Supplemental Content