Observable C++ expressions – using the Observable library

The Observable C++ library has a new feature: observable expressions.

You can create an expression out of observable values and properties, and its result will also be an observable value. The result will stay updated when the expression’s operands change.

A simple example

Some more details

Observable expressions are just like regular C++ expressions, except that instead of being evaluated only once, they are evaluated each time one of their operands changes.

Take the following code:

This is just some regular C++ code; it will compute the average of two numbers. We’ve all seen this kind of code before and we all know how it works.

It works, but what if your operands change? Well, obviously, we’ll need to recompute the average!

See, easy! We just need to create a function that computes an average, and each time we change one number we call that function and update the average.

Let’s try it with the Observable library, using observable values:

The new code is much simpler, right?

You can also subscribe to changes and get notified when the avg changes.

The library supports much more complex expressions than our simple average. You can use mathematical functions, select between two values and even create your own functions (called filters).

Check out the expression documentation for more examples and a more detailed explanation.

How this works, from 10k feet

The quick and simple explanation is this: the library provides overloaded operators for value<T>s.

When you use observable values, the overloaded operators return intermediate expression nodes (which also overload the operators).

These expression nodes form an expression tree that can be used to evaluate an arbitrary expression.

The root of this tree is passed to another class, an expression class, which knows how and when to evaluate the expression tree.

The observe() function takes an expression tree and returns an observable value that is linked to an expression. This observable value is updated each time the expression is evaluated.

When you should use observable expressions

If you can tolerate a bit of template machinery behind the scenes, and you want to use a reactive approach to your code, then this is for you.

Observable expressions can simplify your code and they can make it more readable than the equivalent code.

Check out the Capture The Dot Game and see how observable expressions are used with Qt.

Check out the Observable library on GitHub: https://github.com/ddinu/observable.