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.
4 
5 #ifndef BASE_TASK_RUNNER_UTIL_H_
6 #define BASE_TASK_RUNNER_UTIL_H_
7 
8 #include <memory>
9 #include <utility>
10 
11 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/check.h"
14 #include "base/post_task_and_reply_with_result_internal.h"
15 #include "base/task_runner.h"
16 
17 namespace base {
18 
19 // When you have these methods
20 //
21 //   R DoWorkAndReturn();
22 //   void Callback(const R& result);
23 //
24 // and want to call them in a PostTaskAndReply kind of fashion where the
25 // result of DoWorkAndReturn is passed to the Callback, you can use
26 // PostTaskAndReplyWithResult as in this example:
27 //
28 // PostTaskAndReplyWithResult(
29 //     target_thread_.task_runner(),
30 //     FROM_HERE,
31 //     BindOnce(&DoWorkAndReturn),
32 //     BindOnce(&Callback));
33 //
34 // DEPRECATED: Prefer calling|task_runner->PostTaskAndReplyWithResult(...)|
35 // directly.
36 // TODO(gab): Mass-migrate to the member method.
37 template <typename TaskReturnType, typename ReplyArgType>
PostTaskAndReplyWithResult(TaskRunner * task_runner,const Location & from_here,OnceCallback<TaskReturnType ()> task,OnceCallback<void (ReplyArgType)> reply)38 bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
39                                 const Location& from_here,
40                                 OnceCallback<TaskReturnType()> task,
41                                 OnceCallback<void(ReplyArgType)> reply) {
42   DCHECK(task);
43   DCHECK(reply);
44   // std::unique_ptr used to avoid the need of a default constructor.
45   auto* result = new std::unique_ptr<TaskReturnType>();
46   return task_runner->PostTaskAndReply(
47       from_here,
48       BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, std::move(task),
49                result),
50       BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
51                std::move(reply), Owned(result)));
52 }
53 
54 }  // namespace base
55 
56 #endif  // BASE_TASK_RUNNER_UTIL_H_
57