Skip to content
schlangster edited this page May 24, 2014 · 8 revisions

Motivation

The previously introduced signals revolve around change propagation of persistent data, but those are not the only types events that exist in a program. Button presses or the resize of a window are not something that is meant to be stored; they should rather should trigger certain actions.

When implemented with basic callback registries, things get difficult as soon as actions can no longer be attributed to a single event cause, but happen under more complex conditions. This problem is resolved by introducing event streams as first class objects. As such, they can be composed, merged, filtered or transformed.

The underlying propagation engine is the same as used for signals, thus offering the same benefits of scalable updating and implicit parallelization.

Tutorials

For each of the following tutorials, these two header files have to be included:

#include "react/Domain.h"
#include "react/Event.h"

A domain is defined as:

REACTIVE_DOMAIN(D);

Hello World

We start by creating an EventSource that can emit strings:

#include <string>
using std::string;

D::EventSourceT<string> mySource = D::MakeEventSource<string>();

Analogously to signals, D::EventSourceT<E> and D::MakeEventSource<E>() are aliases for EventSource<D,E> and MakeEventSource<D,E>().

Next, we add an observer that prints strings emitted by mySource:

Observe(mySource, [] (const string& s) {
    std::cout << s << std::endl;
});

Lastly, we emit a string from the source:

mySource << string("Hello world");

// Or without the operator:
mySource.Emit(string("Hello world"));

Note that the opererator used here is << and not <<= as used for signals. This is to indicate that event streams don't hold values, they only propagate them, whereas signal input combines assignment and change propagation.

It's not uncommon that the value type transported by an event stream is irrelevant and we are only interested in the fact that it happened. For instance, when a button has been clicked. In this case, the value type can be omitted.

We create a second version of the "Hello world" program to demonstrate this:

D::EventSourceT<> helloWorldTrigger = D::MakeEventSource();
Observe(helloWorldTrigger, [] (Token) {
    std::cout << "Hello world" << std::endl;
});

helloWorldTrigger.Emit();

Internally, the value transported by token streams is of type Token, hence an unnamed argument of this type was used for the lambda. Earlier versions of the API allowed to omit the event argument completely if it's a token, but for consistency reasons it always has to be declared now.

Merging event streams

Filtering events

Transforming events

Queuing multiple inputs

D::DoTransaction([] {
    src << 1 << 2 << 3;
    src << 4;
});
Observe(src, [] (int v) {
    std::cout << v << std::endl;
}); // 1, 2, 3, 4

Details

TODO

Clone this wiki locally