Option 3: Accept an Event or Callback (to "Push" to Caller)
Both of the alternatives we've just seen let the callee return a "future," which by default delivers a "pull" notification the caller can wait for. So far, we've left it to the caller to turn that "future" into a "push" notification (event or message) if it wants to be proactively notified when the result is available.
What if we want our callee to always offer proactive "push" notifications? The most general way to do that is to accept a callback to be invoked when the result is available:
// Example 3: Return value, using a callback
class Backgrounder {
public:
void Save(
string filename,
function<void(bool)> returnCallback
) {
a.Send( [=] {
// … do the saving work …
returnCallback( didItSucceed() ? true : false );
} ); }
This is especially useful if the caller is itself an active object and gives a callback that is one of its own (asynchronous) methods. For example, this might be used from a GUI thread as follows:
class MyGUI {
public:
// …
// When the user clicks [Save]
void OnSaveClick() {
// …
// … turn on saving icon, etc. …
// …
// pass a continuation to be called to give
// us the result once it's available
shared_future<bool> result;
result = backgrounder.Save( filename,
[=] { SendSaveComplete( result->get() ); } );
}
void OnSaveComplete( bool returnedValue ) {
// … turn off saving icon, etc. …
}
Since Example 3 uses a callback, it's worth mentioning a drawback common to all callback styles, namely: The callback runs on the callee's thread. In the aforementioned code that's not a problem because all the callback does is launch an asynchronous message event that gets queued up for the caller. But remember, it's always a good idea to do as little work as possible in the callee, and just firing off an asynchronous method call and immediately returning is a good practice for callbacks.


