1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_TASK_RUNNER_UTIL_H_
6 #define BASE_TASK_RUNNER_UTIL_H_
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/callback.h"
14 #include "base/logging.h"
15 #include "base/post_task_and_reply_with_result_internal.h"
16 #include "base/task_runner.h"
20 // When you have these methods
22 // R DoWorkAndReturn();
23 // void Callback(const R& result);
25 // and want to call them in a PostTaskAndReply kind of fashion where the
26 // result of DoWorkAndReturn is passed to the Callback, you can use
27 // PostTaskAndReplyWithResult as in this example:
29 // PostTaskAndReplyWithResult(
30 // target_thread_.task_runner(),
32 // BindOnce(&DoWorkAndReturn),
33 // BindOnce(&Callback));
34 template <typename TaskReturnType, typename ReplyArgType>
35 bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
36 const Location& from_here,
37 OnceCallback<TaskReturnType()> task,
38 OnceCallback<void(ReplyArgType)> reply) {
41 // std::unique_ptr used to avoid the need of a default constructor.
42 auto* result = new std::unique_ptr<TaskReturnType>();
43 return task_runner->PostTaskAndReply(
45 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, std::move(task),
47 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
48 std::move(reply), Owned(result)));
51 // Callback version of PostTaskAndReplyWithResult above.
52 // Though RepeatingCallback is convertible to OnceCallback, we need this since
53 // we cannot use template deduction and object conversion at once on the
54 // overload resolution.
55 // TODO(crbug.com/714018): Update all callers of the Callback version to use
57 template <typename TaskReturnType, typename ReplyArgType>
58 bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
59 const Location& from_here,
60 Callback<TaskReturnType()> task,
61 Callback<void(ReplyArgType)> reply) {
62 return PostTaskAndReplyWithResult(
63 task_runner, from_here, OnceCallback<TaskReturnType()>(std::move(task)),
64 OnceCallback<void(ReplyArgType)>(std::move(reply)));
69 #endif // BASE_TASK_RUNNER_UTIL_H_