Tag Archives: c#

A C++ Background Ticker, now with Rx.cpp

Finally, Rx.cpp

Some time ago I have written that I didn’t have enough patience to recreate the background ticker example in C++ using Rx.cpp. Since then the Rx.cpp project seems to have grown out of the spike phase, and even has a native NuGet package. It has also gone multiplatform (Windows, OSX and Linux): observe the green Travis-CI Button.

Update: new blog post, discussing RxCpp v2 and testing using the test scheduler.

A simple console ticker

As in .Net, Reactive Extensions provide a simple way to process streams of data asynchronously, while keeping the concurrency-related code declarative and thus readable. Here’s a simple ticker in the console which runs asynchronously to the main thread:

auto scheduler = std::make_shared<rxcpp::EventLoopScheduler>();
auto ticker = rxcpp::Interval(std::chrono::milliseconds(250), scheduler);

rxcpp::from(ticker)
	.where([](int val) { return val % 2 == 0; })
	.take(10)
	.subscribe([](int val) {
		std::cout << "tick " << val << std::endl;
	});

std::cout << "starting to tick" << std::endl;

resulting in something like:

starting to tick
tick 0
tick 2
tick 4
tick 6
tick 8
...

where the ticks appear once in 250 milliseconds.

Throwing away code

The PPL example was simulating polling a sensor and printing the value. It had an error-prone and buggy ad-hoc implementation of an active object, ticking at predefined intervals. This can be now happily thrown away, as Rx allows a cleaner concurrency control and testability using schedulers, and implements a timed sequence: Interval.

Preconditions

FrequencyMeter FM;
auto scheduler = std::make_shared<rxcpp::EventLoopScheduler>();

The scheduler will be used for all subscriptions.

The tickers

The first one:

auto measure = rxcpp::Interval(std::chrono::milliseconds(250),scheduler);
auto measure_subscription = rxcpp::from(measure)
	.subscribe([&FM](int val) {
		std::cout << FM.Hz() << std::endl;
	});

where measure_subscription is a rxcpp::Disposable for subscription lifetime control.

And the other one:

auto ticker = rxcpp::Interval(std::chrono::milliseconds(500), scheduler);
rxcpp::from(ticker)
	.take(10)
	.subscribe([](int val) {
		std::cout << "tick " << val << std::endl;
	});

where you can observe the LINQ-style filter take

Managing subscriptions

In the PPL example, one could start and stop the ticker. However, in Rx.cpp this can be simply modeled by disposable subscriptions. Hence, after some kind of sleeping, the measurement can be stopped:

sleep(2000);
std::cout << "Canceling measurement ..." << std::endl;
measure_subscription.Dispose(); // cancel measurement

Resulting in similar output:

60
63
tick 0
61
62
tick 1
63
63
tick 2
62
60
tick 3
Canceling measurement ...
tick 4
tick 5
tick 6
tick 7
tick 8
tick 9

Restarting measurement can be done by creating a new subscription.

Why not simply signals/slots?

Almost quoting the Intro to Rx book, the advantages of using Rx over (at least) simple implementations of signal/slot mechanism are:

  • Better maintainability due to readable, composable, declarative code
  • Scheduler abstraction allowing for fast, deterministic, clock-independent tests of concurrency concerns
  • Declarative concurrency through the same scheduler abstraction
  • LINQ-like composition and filtering of event streams
  • Easy subscription control via disposables
  • Completion and exception handling built-in in the Observer concept

Code

@GitHub

Corrections, suggestions and comments are welcome!

Update 26.6.2014: There’s been a new release of Rx.cpp on nuget, and Kirk Shoop pushed a pull request, upgrading the project and the api usage to Rx.cpp 2.0.0. There have been some changes, and there are some interesting patterns, which should be blogged about in the near future.

header-only non-intrusive json serialization in c++

A while ago I’ve started a convenience, zero error-handling, json serializer wrapper around picojson based on the Boost.Serialization and hiberlite APIs. Today the wrapper got even less intrusive for DTOs that expose their members.

Given a class that cannot be extended in its declaration, but the internals are accessible (following to the Boost.Serialization free function API):

struct Untouchable {
    int value;
};

With a free function defined in the ::picojson::convert namespace,

namespace picojson {
    namespace convert {

        template <class Archive>
        void json(Archive &ar, Untouchable &u) {
            ar &picojson::convert::member("value", u.value);
        }

    }
}

serialization is “again” possible:

Untouchable example = { 42 };
std::string example_string( picojson::convert::to_string(example) );

Untouchable example_deserialized = { 0 };
picojson::convert::from_string( example_string, example_deserialized );
CHECK( example.value == example_deserialized.value );

github.com/d-led/picojson_serializer

The quest for a c++ Dependency Injection Container library. Part 3, beginning dicpp

Dependency Injection + C++ = dicpp

The first article introduced the example problem – an almost trivial example for dependency injection. One of the implementation classes is mocked within a test to show the resulting implementation configuration flexibility.

Another library in the quest is dicpp. It is somewhat similar to sauce with little twists, hence it required some trial and error to get right after sauce. Dicpp configures the dependencies in code and allows configurable lifetime scopes.

Modules

Modules are, again, similar to sauce’s modules, as they can be simple functions for registering the bindings of interfaces to implementations.

The library uses a slightly intrusive macro that puts a special typedef in the class’ declaration. One constructor is supported and should be split into declaration and definition. The macro for the renderer looks as follows:

class DicppKeyRenderer : public IRender {
public:
	DI_CONSTRUCTOR(DicppKeyRenderer,(std::shared_ptr< IGetKeyValue > m));
...
};

Without changing the existing factory, the default implementations are used:

DicppKeyRenderer::DicppKeyRenderer(std::shared_ptr< IGetKeyValue > m) :
	pimpl ( NewKeyRenderer(m) ) { }

The module with the bindings looks as follows (dicpp_module.cpp):

void dicpp_module( di::registry& r ) {
	r.add( r.type< IGetKeyValue >().implementation<DicppJsonDecoder>() );
	r.add( r.type< IRender >     ().implementation<DicppKeyRenderer>() );
}

Mock and the Singleton scope

To set the mock expectations on an instance of a dependency, one needs to obtain a pointer to that dependency. Once again, the mock implementation of an interface is done via googlemock:

class MockModel : public IModel {
public:
	MOCK_METHOD0(Get, std::string());
};

To obtain the same instance of the mocked IModel as which gets resolved automatically, one can use a dedicated scope, such as the singleton scope. The mock is added to the module in the singleton scope:

void mock_module( di::registry& r ) {
	r.add( r
		.type<IModel>()
		.implementation<MockModel>()
		.in_scope<di::scopes::singleton>() )
	;
}

Configuring the injector

test_dicpp.cpp

The injector is the container of bindings that gets configured by adding modules:

di::injector inj;
inj.install( dicpp_module );
inj.install( mock_module );

Configuring the mock

With the modules “installed” in the injector, the singleton mock instance can be obtained:

auto mock_model = inj.construct_ptr< IModel >();

MockModel* mock_model_ptr = dynamic_cast< MockModel* >(mock_model.get());
ASSERT_TRUE( mock_model_ptr );

EXPECT_CALL(*mock_model_ptr, Get())
	.Times(AtLeast(1))
	.WillRepeatedly(Return("{ \"a\" : 1 , \"b\" : 2 }"));

Logging in dicpp

An interesting feature in dicpp is logging of the library activity. The feature can be overridden or turned off via macro definition. The construction of dependencies can be traced, such as here, slightly shortened :

[DICPP]: Registering: IGetKeyValue with implementation: DicppJsonDecoder in scope: di::scopes::no_scope
[DICPP]: Registering: IModel with implementation: MockModel in scope: di::scopes::singleton
[DICPP]: Registering: MockModel with implementation: MockModel in scope: di::scopes::no_scope
[DICPP]: Constructing: di::type_key<IModel, void>
[DICPP]: Provided type: di::type_key<IModel, void>
[DICPP]: Singleton: constructing: di::type_key<IModel, void>
[DICPP]: Generic constructing IModel with implementation: MockModel
[DICPP]: Completed constructing: di::type_key<IModel, void> with address: 0x7fd0b2600e40
...
[DICPP]: Singleton: returning existing: di::type_key<IModel, void>

As one can see, two bindings are registered for one implementation – the interface and implementation can be resolved at later time.

Summary

The rest of the example is very similar to the first and the second parts of the quest:

auto renderer = inj.construct_ptr< IRender >();
ASSERT_EQ( "a,b", renderer->Render() );

Although the library is very similar to sauce, the binding definition language doesn’t read as fluently as that of wallaroo or sauce. Further articles may elaborate on the outstanding features of either library.

Source: https://github.com/d-led/test-ioc-cpp

Updates

05.11.2014: Removed boost<->std shared_ptr conversions, as dicpp has been updated in the meanwhile

More to come…