Tutorial » Transforming continuables

Explains the conversion into other types such as std::future.

Transforms in general

Sometimes it's required to change a continuable_base object by its whole. Thus the library offers the ability to apply a transformation to any continuable_base through using apply.

A transformation is a callable object that accepts a continuable_base and returns an arbitrary object

The library provides several transforms already as part of the cti::transforms namespace.

Synchronous wait

The library is capable of converting every asynchronous control flow into a synchronous one through transforms::wait, transforms::wait_for and transforms::wait_until.

std::string response = http_request("github.com")
  .apply(cti::transforms::wait());

std::string response = http_request("github.com")
  .apply(cti::transforms::wait_for(std::chrono::seconds(5)));

std::string response = http_request("github.com")
  .apply(cti::transforms::wait_until(...));

The current thread will be blocked until the result has arrived

Conversion into std::future

The library is capable of converting (futurizing) every continuable into a fitting std::future through the transforms::to_future transform:

std::future<std::string> future = http_request("github.com")
  .then([](std::string response) {
    // Do sth...
    return http_request("travis-ci.org") || http_request("atom.io");
  })
  .apply(cti::transforms::to_future());
// ^^^^^^^^

Multiple arguments which can't be handled by std::future itself are converted into std::tuple, see transforms::to_future for details.

std::future<std::tuple<std::string, std::string>> future =
  (http_request("travis-ci.org") && http_request("atom.io"))
    .apply(cti::transforms::to_future());