summaryrefslogtreecommitdiff
path: root/Rx/v2/src/rxcpp/subjects/rx-synchronize.hpp
blob: 858eef31a96ddbf25f0e51cb172016d37f516692 (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

#if !defined(RXCPP_RX_SYNCHRONIZE_HPP)
#define RXCPP_RX_SYNCHRONIZE_HPP

#include "../rx-includes.hpp"

namespace rxcpp {

namespace subjects {

namespace detail {

template<class T, class Coordination>
class synchronize_observer : public detail::multicast_observer<T>
{
    typedef synchronize_observer<T, Coordination> this_type;
    typedef detail::multicast_observer<T> base_type;

    typedef rxu::decay_t<Coordination> coordination_type;
    typedef typename coordination_type::coordinator_type coordinator_type;
    typedef typename coordinator_type::template get<subscriber<T>>::type output_type;

    struct synchronize_observer_state : public std::enable_shared_from_this<synchronize_observer_state>
    {
        typedef rxn::notification<T> notification_type;
        typedef typename notification_type::type base_notification_type;
        typedef std::deque<base_notification_type> queue_type;

        struct mode
        {
            enum type {
                Invalid = 0,
                Processing,
                Empty,
                Disposed
            };
        };

        mutable std::mutex lock;
        mutable std::condition_variable wake;
        mutable queue_type fill_queue;
        composite_subscription lifetime;
        mutable typename mode::type current;
        coordinator_type coordinator;
        output_type destination;

        void ensure_processing(std::unique_lock<std::mutex>& guard) const {
            if (!guard.owns_lock()) {
                std::terminate();
            }
            if (current == mode::Empty) {
                current = mode::Processing;
                auto keepAlive = this->shared_from_this();

                auto drain_queue = [keepAlive, this](const rxsc::schedulable& self){
                    RXCPP_TRY {
                        std::unique_lock<std::mutex> guard(lock);
                        if (!destination.is_subscribed()) {
                            current = mode::Disposed;
                            fill_queue.clear();
                            guard.unlock();
                            lifetime.unsubscribe();
                            return;
                        }
                        if (fill_queue.empty()) {
                            current = mode::Empty;
                            return;
                        }
                        auto notification = std::move(fill_queue.front());
                        fill_queue.pop_front();
                        guard.unlock();
                        notification->accept(destination);
                        self();
                    } RXCPP_CATCH(...) {
                        destination.on_error(rxu::current_exception());
                        std::unique_lock<std::mutex> guard(lock);
                        current = mode::Empty;
                    }
                };

                auto selectedDrain = on_exception(
                    [&](){return coordinator.act(drain_queue);},
                    destination);
                if (selectedDrain.empty()) {
                    return;
                }

                auto processor = coordinator.get_worker();
                processor.schedule(lifetime, selectedDrain.get());
            }
        }

        synchronize_observer_state(coordinator_type coor, composite_subscription cs, output_type scbr)
            : lifetime(std::move(cs))
            , current(mode::Empty)
            , coordinator(std::move(coor))
            , destination(std::move(scbr))
        {
        }

        template<class V>
        void on_next(V v) const {
            if (lifetime.is_subscribed()) {
                std::unique_lock<std::mutex> guard(lock);
                fill_queue.push_back(notification_type::on_next(std::move(v)));
                ensure_processing(guard);
            }
            wake.notify_one();
        }
        void on_error(rxu::error_ptr e) const {
            if (lifetime.is_subscribed()) {
                std::unique_lock<std::mutex> guard(lock);
                fill_queue.push_back(notification_type::on_error(e));
                ensure_processing(guard);
            }
            wake.notify_one();
        }
        void on_completed() const {
            if (lifetime.is_subscribed()) {
                std::unique_lock<std::mutex> guard(lock);
                fill_queue.push_back(notification_type::on_completed());
                ensure_processing(guard);
            }
            wake.notify_one();
        }
    };

    std::shared_ptr<synchronize_observer_state> state;

public:
    synchronize_observer(coordination_type cn, composite_subscription dl, composite_subscription il)
        : base_type(dl)
    {
        auto o = make_subscriber<T>(dl, make_observer_dynamic<T>( *static_cast<base_type*>(this) ));

        // creates a worker whose lifetime is the same as the destination subscription
        auto coordinator = cn.create_coordinator(dl);

        state = std::make_shared<synchronize_observer_state>(std::move(coordinator), std::move(il), std::move(o));
    }

    subscriber<T> get_subscriber() const {
        return make_subscriber<T>(this->get_id(), state->lifetime, observer<T, detail::synchronize_observer<T, Coordination>>(*this)).as_dynamic();
    }

    template<class V>
    void on_next(V v) const {
        state->on_next(std::move(v));
    }
    void on_error(rxu::error_ptr e) const {
        state->on_error(e);
    }
    void on_completed() const {
        state->on_completed();
    }
};

}

template<class T, class Coordination>
class synchronize
{
    detail::synchronize_observer<T, Coordination> s;

public:
    explicit synchronize(Coordination cn, composite_subscription cs = composite_subscription())
        : s(std::move(cn), std::move(cs), composite_subscription())
    {
    }

    bool has_observers() const {
        return s.has_observers();
    }

    subscriber<T> get_subscriber() const {
        return s.get_subscriber();
    }

    observable<T> get_observable() const {
        auto keepAlive = s;
        return make_observable_dynamic<T>([=](subscriber<T> o){
            keepAlive.add(keepAlive.get_subscriber(), std::move(o));
        });
    }
};

}

class synchronize_in_one_worker : public coordination_base
{
    rxsc::scheduler factory;

    class input_type
    {
        rxsc::worker controller;
        rxsc::scheduler factory;
        identity_one_worker coordination;
    public:
        explicit input_type(rxsc::worker w)
            : controller(w)
            , factory(rxsc::make_same_worker(w))
            , coordination(factory)
        {
        }
        inline rxsc::worker get_worker() const {
            return controller;
        }
        inline rxsc::scheduler get_scheduler() const {
            return factory;
        }
        inline rxsc::scheduler::clock_type::time_point now() const {
            return factory.now();
        }
        template<class Observable>
        auto in(Observable o) const
            -> decltype(o.publish_synchronized(coordination).ref_count()) {
            return      o.publish_synchronized(coordination).ref_count();
        }
        template<class Subscriber>
        auto out(Subscriber s) const
            -> Subscriber {
            return s;
        }
        template<class F>
        auto act(F f) const
            -> F {
            return f;
        }
    };

public:

    explicit synchronize_in_one_worker(rxsc::scheduler sc) : factory(sc) {}

    typedef coordinator<input_type> coordinator_type;

    inline rxsc::scheduler::clock_type::time_point now() const {
        return factory.now();
    }

    inline coordinator_type create_coordinator(composite_subscription cs = composite_subscription()) const {
        auto w = factory.create_worker(std::move(cs));
        return coordinator_type(input_type(std::move(w)));
    }
};

inline synchronize_in_one_worker synchronize_event_loop() {
    static synchronize_in_one_worker r(rxsc::make_event_loop());
    return r;
}

inline synchronize_in_one_worker synchronize_new_thread() {
    static synchronize_in_one_worker r(rxsc::make_new_thread());
    return r;
}

}

#endif