summaryrefslogtreecommitdiff
path: root/include/mbgl/storage/default/shared_request_base.hpp
blob: 2d56615608054d8c8779ea9da5e18e444eec7df7 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#ifndef MBGL_STORAGE_DEFAULT_SHARED_REQUEST_BASE
#define MBGL_STORAGE_DEFAULT_SHARED_REQUEST_BASE

#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/file_cache.hpp>
#include <mbgl/storage/default_file_source.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/noncopyable.hpp>

#include <string>
#include <set>
#include <cassert>

typedef struct uv_loop_s uv_loop_t;

namespace mbgl {

class Request;
class Response;
class DefaultFileSource;

class SharedRequestBase : private util::noncopyable {
protected:
    MBGL_STORE_THREAD(tid)

public:
    SharedRequestBase(DefaultFileSource *source_, const Resource &resource_)
        : resource(resource_), source(source_) {}

    virtual void start(uv_loop_t *loop, std::unique_ptr<Response> response = nullptr) = 0;
    virtual void cancel() = 0;

    void notify(std::unique_ptr<Response> response, FileCache::Hint hint) {
        MBGL_VERIFY_THREAD(tid);

        if (source) {
            source->notify(this, observers, std::shared_ptr<const Response>(std::move(response)),
                           hint);
        }
    }

    void subscribe(Request *request) {
        MBGL_VERIFY_THREAD(tid);

        observers.insert(request);
    }

    void unsubscribeAll() {
        MBGL_VERIFY_THREAD(tid);

        source = nullptr;
        observers.clear();
        cancel();
    }

    void unsubscribe(Request *request) {
        MBGL_VERIFY_THREAD(tid);

        observers.erase(request);

        if (observers.empty()) {
            // There are no observers anymore. We are initiating cancelation.
            if (source) {
                // First, remove this SharedRequestBase from the source.
                source->notify(this, observers, nullptr, FileCache::Hint::No);
            }

            // Then, initiate cancelation of this request
            cancel();
        }
    }

protected:
    virtual ~SharedRequestBase() {
        MBGL_VERIFY_THREAD(tid);
    }

public:
    const Resource resource;

protected:
    DefaultFileSource *source = nullptr;

private:
    std::set<Request *> observers;
};

}

#endif