Reactive Programming is really great to write event driven applications, data driven applications, and asynchronous applications. However, it can be difficult to find a good way to structure the code. Fortunately for JavaScript developers, there is CycleJs. So I developed a similar framework for Python and RxPYCyclotron.

edit 2020/10: Updated examples to RxPY v3, and cyclotron drivers list.

Cyclotron is a functional and reactive framework. It allows structuring reactive code in a functional way. More specifically, functional means the following:

  • Pure code and side effects are clearly separated
  • All the code is implemented via functions (no class)

Moreover, it is specifically designed to write reactive code:

  • All components communicate via Observables
  • Observables cycles are naturally handled

The following pictures show how a Cyclotron application is structured

There are two parts to a cyclotron application: A pure data-flow, and side effects. The pure data-flow is composed of pure functions. Pure functions are functions whose behavior is deterministic. This means that their output depends only on their input parameters. The pure data-flow part is where the application logic is implemented.

A side effect is any function that is not a pure function. For example, a function that takes no parameter as input and returns the current date is a side effect. Also, any function that works on IO is a side effect because its result depends on the underlying IO.

The pure data flow and the side effects communicate together via Observables. By convention, the output Observables of the pure data flow (that is also the input of side effects) are called sinks. The input Observables subscribed by the pure data-flow (being also the output of the side effects) are called sources.

Note how the pure data-flow and the side effects form a directed cyclic graph: They depend on each other. Managing such Observable cycles is not always easy. Cyclotron handles naturally such cycles between the pure data-flow and the side effects: A bootstrap function connects circularly the pure entry point with the side effects.

Let’s see an example application. A hello world consisting of an asynchronous http server that sends back the content received on the “/echo” url. This echo server uses AsyncIO for the asynchronous management of the IO operations. The design of this application is shown on the following reactivity diagram

#reactivex #python #functional-programming #programming

Functional and Reactive Programming in Python with Cyclotron
1.85 GEEK