Monthly Archives: November 2016

Implementing the observer pattern

The Observable C++ library – implementing the observer pattern

TL;DR: Use the Observable C++ library if you need to implement the observer pattern for your C++ project.

Why you should use this library

Whenever I need to subscribe to events, I usually implement some variation of the observer pattern, or (if available) hack and misuse Qt’s signals and slots mechanism to do the job. Because of this, usually I’m not happy with the results; especially if I misuse QObjects.

I hope that we can all agree that using a library is a lot easier than rolling your own. It should also be a lot better than hacking other libraries.

The library is header-only, so you can easily integrate it into your project. If you want to build the tests, they’re using CMake, so that should be easy too.

It works with Microsoft Visual Studio 2015+, GCC 5.4+ and Clang 3.6+ on both Windows and Linux.

Some trivial observer examples

The most basic code that you can write will be using a subject object directly:

Subjects take a “function type” as their template parameter. You can subscribe to notifications using any callable object that can be stored inside a std::function<FunctionType>.

The subscribe() method returns a subscription object. You can keep the subscription object, to use later for unsubscribing, or you can call the release() method and make the subscription live forever.

Subjects also have some code that makes sure you don’t crash if you call unsubscribe() after the subject instance is destroyed.

Your only concern will be to keep the “observer” callable valid while it remains subscribed.

You can also use observable properties:

Properties use subject objects behind the scenes, so everything from above will also apply.

Property setters are private, and by giving the enclosing class as a template parameter, you’ll be able to access the assignment operator. Because of this, properties are more like methods than member variables (and it also makes it much easier to pass code reviews).

Why not just use Boost.Signals2 or Qt?

Boost.Signals2 and Qt are pretty cool libraries and do their jobs well.

This library is not meant to replace signals and slots; it focuses more on providing easy to use observable properties while not being invasive – see the MOC or the limitation on multiple inheritance for QObjects.

Choose whichever library works best for your case; you can even choose them both (for example, have your models use this library and your views use Qt).

Where to get the Observable library

Check out the library’s GitHub page.

There’s also some basic documentation on GitHub.

The Observable library is licensed under the Apache 2 license.

Any bug reports, feature requests, questions or code contributions are welcome.