2018-09-26 10:01:59 -07:00
|
|
|
/**
|
|
|
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
|
|
*
|
|
|
|
* This source code is licensed under the MIT license found in the
|
|
|
|
* LICENSE file in the root directory of this source tree.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <memory>
|
|
|
|
#include <mutex>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
#include <fabric/events/EventBeat.h>
|
|
|
|
|
|
|
|
namespace facebook {
|
|
|
|
namespace react {
|
|
|
|
|
|
|
|
/*
|
|
|
|
* General purpose executor that uses EventBeat to ensure proper threading.
|
|
|
|
*/
|
|
|
|
class EventBeatBasedExecutor {
|
2018-10-09 16:25:13 -07:00
|
|
|
public:
|
2018-09-26 10:01:59 -07:00
|
|
|
using Routine = std::function<void()>;
|
|
|
|
using Callback = std::function<void()>;
|
|
|
|
|
|
|
|
struct Task {
|
|
|
|
Routine routine;
|
|
|
|
Callback callback;
|
|
|
|
};
|
|
|
|
|
2018-10-09 16:25:13 -07:00
|
|
|
enum class Mode { Synchronous, Asynchronous };
|
2018-09-26 10:01:59 -07:00
|
|
|
|
|
|
|
EventBeatBasedExecutor(std::unique_ptr<EventBeat> eventBeat);
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Executes given routine with given mode.
|
|
|
|
*/
|
|
|
|
void operator()(Routine routine, Mode mode = Mode::Asynchronous) const;
|
|
|
|
|
2018-10-09 16:25:13 -07:00
|
|
|
private:
|
2018-10-08 14:34:25 -07:00
|
|
|
void onBeat(bool success = true) const;
|
2018-09-26 10:01:59 -07:00
|
|
|
void execute(Task task) const;
|
|
|
|
|
|
|
|
std::unique_ptr<EventBeat> eventBeat_;
|
|
|
|
mutable std::vector<Task> tasks_; // Protected by `mutex_`.
|
|
|
|
mutable std::mutex mutex_;
|
|
|
|
};
|
|
|
|
|
|
|
|
using EventBeatFactory = std::function<std::unique_ptr<EventBeat>()>;
|
|
|
|
|
|
|
|
} // namespace react
|
|
|
|
} // namespace facebook
|