cancelable_callback.h 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. // CancelableOnceCallback is a wrapper around OnceCallback that allows
  6. // cancellation of the callback. CanacelableRepeatingCallback is the same sort
  7. // of wrapper around RepeatingCallback. The wrapper takes a reference on the
  8. // wrapped callback until this object is destroyed or Reset()/Cancel() are
  9. // called.
  10. //
  11. // NOTE:
  12. //
  13. // Calling Cancel() brings the object back to its natural, default-constructed
  14. // state, i.e., callback() will return a null callback.
  15. //
  16. // THREAD-SAFETY:
  17. //
  18. // Cancelable callback objects must be created on, posted to, cancelled on, and
  19. // destroyed on the same SequencedTaskRunner.
  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. // CancelableOnceClosure timeout(
  37. // base::BindOnce(&TimeoutCallback, "Test timed out."));
  38. // ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, timeout.callback(),
  39. // Seconds(4));
  40. // RunIntensiveTest();
  41. // run_loop.Run();
  42. // timeout.Cancel(); // Hopefully this is hit before the timeout callback runs.
  43. //
  44. #ifndef BASE_CANCELABLE_CALLBACK_H_
  45. #define BASE_CANCELABLE_CALLBACK_H_
  46. #include <utility>
  47. #include "base/bind.h"
  48. #include "base/callback.h"
  49. #include "base/callback_internal.h"
  50. #include "base/check.h"
  51. #include "base/compiler_specific.h"
  52. #include "base/memory/weak_ptr.h"
  53. namespace base {
  54. namespace internal {
  55. template <typename CallbackType>
  56. class CancelableCallbackImpl {
  57. public:
  58. CancelableCallbackImpl() = default;
  59. CancelableCallbackImpl(const CancelableCallbackImpl&) = delete;
  60. CancelableCallbackImpl& operator=(const CancelableCallbackImpl&) = delete;
  61. // |callback| must not be null.
  62. explicit CancelableCallbackImpl(CallbackType callback)
  63. : callback_(std::move(callback)) {
  64. DCHECK(callback_);
  65. }
  66. ~CancelableCallbackImpl() = default;
  67. // Cancels and drops the reference to the wrapped callback.
  68. void Cancel() {
  69. weak_ptr_factory_.InvalidateWeakPtrs();
  70. callback_.Reset();
  71. }
  72. // Returns true if the wrapped callback has been cancelled.
  73. bool IsCancelled() const {
  74. return callback_.is_null();
  75. }
  76. // Sets |callback| as the closure that may be cancelled. |callback| may not
  77. // be null. Outstanding and any previously wrapped callbacks are cancelled.
  78. void Reset(CallbackType callback) {
  79. DCHECK(callback);
  80. // Outstanding tasks (e.g., posted to a message loop) must not be called.
  81. Cancel();
  82. callback_ = std::move(callback);
  83. }
  84. // Returns a callback that can be disabled by calling Cancel().
  85. CallbackType callback() const {
  86. if (!callback_)
  87. return CallbackType();
  88. CallbackType forwarder;
  89. MakeForwarder(&forwarder);
  90. return forwarder;
  91. }
  92. private:
  93. template <typename... Args>
  94. void MakeForwarder(RepeatingCallback<void(Args...)>* out) const {
  95. using ForwarderType = void (CancelableCallbackImpl::*)(Args...);
  96. ForwarderType forwarder = &CancelableCallbackImpl::ForwardRepeating;
  97. *out = BindRepeating(forwarder, weak_ptr_factory_.GetWeakPtr());
  98. }
  99. template <typename... Args>
  100. void MakeForwarder(OnceCallback<void(Args...)>* out) const {
  101. using ForwarderType = void (CancelableCallbackImpl::*)(Args...);
  102. ForwarderType forwarder = &CancelableCallbackImpl::ForwardOnce;
  103. *out = BindOnce(forwarder, weak_ptr_factory_.GetWeakPtr());
  104. }
  105. template <typename... Args>
  106. void ForwardRepeating(Args... args) {
  107. callback_.Run(std::forward<Args>(args)...);
  108. }
  109. template <typename... Args>
  110. void ForwardOnce(Args... args) {
  111. weak_ptr_factory_.InvalidateWeakPtrs();
  112. std::move(callback_).Run(std::forward<Args>(args)...);
  113. }
  114. // The stored closure that may be cancelled.
  115. CallbackType callback_;
  116. mutable base::WeakPtrFactory<CancelableCallbackImpl> weak_ptr_factory_{this};
  117. };
  118. } // namespace internal
  119. // Consider using base::WeakPtr directly instead of base::CancelableOnceCallback
  120. // for task cancellation.
  121. template <typename Signature>
  122. using CancelableOnceCallback =
  123. internal::CancelableCallbackImpl<OnceCallback<Signature>>;
  124. using CancelableOnceClosure = CancelableOnceCallback<void()>;
  125. template <typename Signature>
  126. using CancelableRepeatingCallback =
  127. internal::CancelableCallbackImpl<RepeatingCallback<Signature>>;
  128. using CancelableRepeatingClosure = CancelableRepeatingCallback<void()>;
  129. } // namespace base
  130. #endif // BASE_CANCELABLE_CALLBACK_H_