UNPKG

1.19 kBtext/x-cView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#pragma once
9
10#include <memory>
11#include <mutex>
12#include <vector>
13
14#include <react/events/EventBeat.h>
15
16namespace facebook {
17namespace react {
18
19/*
20 * General purpose executor that uses EventBeat to ensure proper threading.
21 */
22class EventBeatBasedExecutor {
23 public:
24 using Routine = std::function<void()>;
25 using Callback = std::function<void()>;
26
27 struct Task {
28 Routine routine;
29 Callback callback;
30 };
31
32 enum class Mode { Synchronous, Asynchronous };
33
34 EventBeatBasedExecutor(std::unique_ptr<EventBeat> eventBeat);
35
36 /*
37 * Executes given routine with given mode.
38 */
39 void operator()(Routine routine, Mode mode = Mode::Asynchronous) const;
40
41 private:
42 void onBeat(bool success = true) const;
43 void execute(Task task) const;
44
45 std::unique_ptr<EventBeat> eventBeat_;
46 mutable std::vector<Task> tasks_; // Protected by `mutex_`.
47 mutable std::mutex mutex_;
48};
49
50using EventBeatFactory = std::function<std::unique_ptr<EventBeat>()>;
51
52} // namespace react
53} // namespace facebook