• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 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 // CancelableCallback is a wrapper around base::Callback that allows
6 // cancellation of a callback. CancelableCallback takes a reference on the
7 // wrapped callback until this object is destroyed or Reset()/Cancel() are
8 // called.
9 //
10 // NOTE:
11 //
12 // Calling CancelableCallback::Cancel() brings the object back to its natural,
13 // default-constructed state, i.e., CancelableCallback::callback() will return
14 // a null callback.
15 //
16 // THREAD-SAFETY:
17 //
18 // CancelableCallback objects must be created on, posted to, cancelled on, and
19 // destroyed on the same thread.
20 //
21 //
22 // EXAMPLE USAGE:
23 //
24 // In the following example, the test is verifying that RunIntensiveTest()
25 // Quit()s the message loop within 4 seconds. The cancelable callback is posted
26 // to the message loop, the intensive test runs, the message loop is run,
27 // then the callback is cancelled.
28 //
29 // RunLoop run_loop;
30 //
31 // void TimeoutCallback(const std::string& timeout_message) {
32 //   FAIL() << timeout_message;
33 //   run_loop.QuitWhenIdle();
34 // }
35 //
36 // CancelableClosure timeout(base::Bind(&TimeoutCallback, "Test timed out."));
37 // ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, timeout.callback(),
38 //                                                TimeDelta::FromSeconds(4));
39 // RunIntensiveTest();
40 // run_loop.Run();
41 // timeout.Cancel();  // Hopefully this is hit before the timeout callback runs.
42 //
43 
44 #ifndef BASE_CANCELABLE_CALLBACK_H_
45 #define BASE_CANCELABLE_CALLBACK_H_
46 
47 #include <utility>
48 
49 #include "base/base_export.h"
50 #include "base/bind.h"
51 #include "base/callback.h"
52 #include "base/callback_internal.h"
53 #include "base/compiler_specific.h"
54 #include "base/logging.h"
55 #include "base/macros.h"
56 #include "base/memory/weak_ptr.h"
57 
58 namespace base {
59 namespace internal {
60 
61 template <typename CallbackType>
62 class CancelableCallbackImpl {
63  public:
CancelableCallbackImpl()64   CancelableCallbackImpl() : weak_ptr_factory_(this) {}
65 
66   // |callback| must not be null.
CancelableCallbackImpl(CallbackType callback)67   explicit CancelableCallbackImpl(CallbackType callback)
68       : callback_(std::move(callback)), weak_ptr_factory_(this) {
69     DCHECK(callback_);
70   }
71 
72   ~CancelableCallbackImpl() = default;
73 
74   // Cancels and drops the reference to the wrapped callback.
Cancel()75   void Cancel() {
76     weak_ptr_factory_.InvalidateWeakPtrs();
77     callback_.Reset();
78   }
79 
80   // Returns true if the wrapped callback has been cancelled.
IsCancelled()81   bool IsCancelled() const {
82     return callback_.is_null();
83   }
84 
85   // Sets |callback| as the closure that may be cancelled. |callback| may not
86   // be null. Outstanding and any previously wrapped callbacks are cancelled.
Reset(CallbackType callback)87   void Reset(CallbackType callback) {
88     DCHECK(callback);
89     // Outstanding tasks (e.g., posted to a message loop) must not be called.
90     Cancel();
91     callback_ = std::move(callback);
92   }
93 
94   // Returns a callback that can be disabled by calling Cancel().
callback()95   CallbackType callback() const {
96     if (!callback_)
97       return CallbackType();
98     CallbackType forwarder;
99     MakeForwarder(&forwarder);
100     return forwarder;
101   }
102 
103  private:
104   template <typename... Args>
MakeForwarder(RepeatingCallback<void (Args...)> * out)105   void MakeForwarder(RepeatingCallback<void(Args...)>* out) const {
106     using ForwarderType = void (CancelableCallbackImpl::*)(Args...);
107     ForwarderType forwarder = &CancelableCallbackImpl::ForwardRepeating;
108     *out = BindRepeating(forwarder, weak_ptr_factory_.GetWeakPtr());
109   }
110 
111   template <typename... Args>
MakeForwarder(OnceCallback<void (Args...)> * out)112   void MakeForwarder(OnceCallback<void(Args...)>* out) const {
113     using ForwarderType = void (CancelableCallbackImpl::*)(Args...);
114     ForwarderType forwarder = &CancelableCallbackImpl::ForwardOnce;
115     *out = BindOnce(forwarder, weak_ptr_factory_.GetWeakPtr());
116   }
117 
118   template <typename... Args>
ForwardRepeating(Args...args)119   void ForwardRepeating(Args... args) {
120     callback_.Run(std::forward<Args>(args)...);
121   }
122 
123   template <typename... Args>
ForwardOnce(Args...args)124   void ForwardOnce(Args... args) {
125     weak_ptr_factory_.InvalidateWeakPtrs();
126     std::move(callback_).Run(std::forward<Args>(args)...);
127   }
128 
129   // The stored closure that may be cancelled.
130   CallbackType callback_;
131   mutable base::WeakPtrFactory<CancelableCallbackImpl> weak_ptr_factory_;
132 
133   DISALLOW_COPY_AND_ASSIGN(CancelableCallbackImpl);
134 };
135 
136 }  // namespace internal
137 
138 // Consider using base::WeakPtr directly instead of base::CancelableCallback for
139 // the task cancellation.
140 template <typename Signature>
141 using CancelableOnceCallback =
142     internal::CancelableCallbackImpl<OnceCallback<Signature>>;
143 using CancelableOnceClosure = CancelableOnceCallback<void()>;
144 
145 template <typename Signature>
146 using CancelableRepeatingCallback =
147     internal::CancelableCallbackImpl<RepeatingCallback<Signature>>;
148 using CancelableRepeatingClosure = CancelableOnceCallback<void()>;
149 
150 template <typename Signature>
151 using CancelableCallback = CancelableRepeatingCallback<Signature>;
152 using CancelableClosure = CancelableCallback<void()>;
153 
154 }  // namespace base
155 
156 #endif  // BASE_CANCELABLE_CALLBACK_H_
157