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 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | namespace facebook {
|
16 | namespace react {
|
17 |
|
18 | /*
|
19 | * Event Beat serves two interleaving purposes: synchronization of event queues
|
20 | * and ensuring that event dispatching happens on propper threads.
|
21 | */
|
22 | class EventBeat {
|
23 | public:
|
24 | virtual ~EventBeat() = default;
|
25 |
|
26 | using BeatCallback = std::function<void(jsi::Runtime &runtime)>;
|
27 | using FailCallback = std::function<void()>;
|
28 |
|
29 | /*
|
30 | * Communicates to the Beat that a consumer is waiting for the coming beat.
|
31 | * A consumer must request coming beat after the previous beat happened
|
32 | * to receive a next coming one.
|
33 | */
|
34 | virtual void request() const;
|
35 |
|
36 | /*
|
37 | * Induces the next beat to happen as soon as possible. If the method
|
38 | * is called on the proper thread, the beat must happen synchronously.
|
39 | * Subclasses might override this method to implement specific
|
40 | * out-of-turn beat scheduling.
|
41 | * Some types of Event Beats do not support inducing, hence the default
|
42 | * implementation does nothing.
|
43 | * Receiver might ignore the call if a beat was not requested.
|
44 | */
|
45 | virtual void induce() const;
|
46 |
|
47 | /*
|
48 | * Sets the beat callback function.
|
49 | * The callback is must be called on the proper thread.
|
50 | */
|
51 | void setBeatCallback(const BeatCallback &beatCallback);
|
52 |
|
53 | /*
|
54 | * Sets the fail callback function.
|
55 | * Called in case if the beat cannot be performed anymore because of
|
56 | * some external circumstances (e.g. execution thread is beling destructed).
|
57 | * The callback can be called on any thread.
|
58 | */
|
59 | void setFailCallback(const FailCallback &failCallback);
|
60 |
|
61 | /*
|
62 | * Should be used by sublasses to send a beat.
|
63 | * Receiver might ignore the call if a beat was not requested.
|
64 | */
|
65 | void beat(jsi::Runtime &runtime) const;
|
66 |
|
67 | protected:
|
68 | BeatCallback beatCallback_;
|
69 | FailCallback failCallback_;
|
70 | mutable std::atomic<bool> isRequested_{false};
|
71 | };
|
72 |
|
73 | using EventBeatFactory = std::function<std::unique_ptr<EventBeat>()>;
|
74 |
|
75 | } // namespace react
|
76 | } // namespace facebook
|