1 /*
2  * Copyright 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <base/callback.h>
20 #include <base/functional/bind.h>
21 #include <base/location.h>
22 
23 #include "stack/include/main_thread.h"
24 
25 namespace bluetooth {
26 
27 class ModuleMainloop {
28  protected:
29   ModuleMainloop() noexcept = default;
30   virtual ~ModuleMainloop() = default;
31   ModuleMainloop(const ModuleMainloop& mod) = delete;
32 
33   // Threadsafe post onto mainloop a function with copyable arguments
34   template <typename Functor, typename... Args>
PostFunctionOnMain(Functor && functor,Args &&...args)35   void PostFunctionOnMain(Functor&& functor, Args&&... args) const {
36     do_in_main_thread(
37         FROM_HERE, base::BindOnce(std::forward<Functor>(functor), std::forward<Args>(args)...));
38   }
39 
40   // Threadsafe post onto mainloop a method and context with copyable arguments
41   template <typename T, typename Functor, typename... Args>
PostMethodOnMain(std::shared_ptr<T> ref,Functor && functor,Args...args)42   void PostMethodOnMain(std::shared_ptr<T> ref, Functor&& functor, Args... args) const {
43     do_in_main_thread(
44         FROM_HERE,
45         base::BindOnce(
46             [](std::weak_ptr<T> ref, Functor&& functor, Args&&... args) {
47               if (std::shared_ptr<T> spt = ref.lock()) {
48                 base::BindOnce(std::forward<Functor>(functor), spt, std::forward<Args>(args)...)
49                     .Run();
50               }
51             },
52             std::weak_ptr<T>(ref),
53             std::forward<Functor>(functor),
54             std::forward<Args>(args)...));
55   }
56 };
57 
58 }  // namespace bluetooth
59