summaryrefslogtreecommitdiff
path: root/platform/android/src/async_task.cpp
blob: 7b78eadb0c74ad6f2c17bb4b825c0abe2df24736 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "run_loop_impl.hpp"

#include <mbgl/util/async_task.hpp>
#include <mbgl/util/run_loop.hpp>

#include <atomic>
#include <functional>

namespace mbgl {
namespace util {

class AsyncTask::Impl : public RunLoop::Impl::Runnable {
public:
    Impl(std::function<void()>&& fn)
        : queued(true), task(std::move(fn)) {
        loop->initRunnable(this);
    }

    ~Impl() {
        loop->removeRunnable(this);
    }

    void maySend() {
        if (queued) {
            queued = false;
            loop->addRunnable(this);
        }
    }

    TimePoint dueTime() const override {
        return due;
    }

    void runTask() override {
        loop->removeRunnable(this);
        queued = true;
        task();
    }

private:
    // Always expired, run immediately.
    const TimePoint due = Clock::now();

    RunLoop::Impl* loop = reinterpret_cast<RunLoop::Impl*>(RunLoop::getLoopHandle());

    // TODO: Use std::atomic_flag if we ever drop
    // support for ARMv5
    std::atomic<bool> queued;
    std::function<void()> task;
};

AsyncTask::AsyncTask(std::function<void()>&& fn)
    : impl(std::make_unique<Impl>(std::move(fn))) {
}

AsyncTask::~AsyncTask() = default;

void AsyncTask::send() {
    impl->maySend();
}

} // namespace util
} // namespace mbgl