ReactivePlusPlus
One more implementation of ReactiveX approach in C++ with care about performance and templates in mind
 
Loading...
Searching...
No Matches
main_thread_scheduler.hpp
1// ReactivePlusPlus library
2//
3// Copyright Aleksey Loginov 2022 - present.
4// Distributed under the Boost Software License, Version 1.0.
5// (See accompanying file LICENSE_1_0.txt or copy at
6// https://www.boost.org/LICENSE_1_0.txt)
7//
8// Project home: https://github.com/victimsnino/ReactivePlusPlus
9//
10
11#pragma once
12
13#include <rppqt/schedulers/fwd.hpp> // own forwarding
14#include <rpp/schedulers/details/worker.hpp> // worker
15#include <rpp/subscriptions/subscription_base.hpp> // lifetime
16#include <rppqt/utils/exceptions.hpp>
17
18#include <chrono>
19#include <concepts>
20
21#include <QCoreApplication>
22#include <QTimer>
23
24namespace rppqt::schedulers
25{
31{
32private:
33 class worker_strategy;
35
36 class worker_strategy
37 {
38 public:
39 worker_strategy(const rpp::subscription_base& sub)
40 : m_sub{sub} {}
41
42 bool is_subscribed() const { return m_sub.is_subscribed(); }
43
44 void defer_at(rpp::schedulers::time_point time_point, rpp::schedulers::constraint::schedulable_fn auto&& fn) const
45 {
46 defer_at(time_point, main_thread_schedulable{*this, time_point, std::forward<decltype(fn)>(fn)});
47 }
48
49 void defer_at(rpp::schedulers::time_point time_point, main_thread_schedulable&& fn) const
50 {
51 if (!m_sub.is_subscribed())
52 return;
53
54 const auto application = QCoreApplication::instance();
55 if (!application)
57 "Pointer to application is null. Create QApplication before using main_thread_scheduler!"};
58
59 const auto duration = std::max(std::chrono::milliseconds{0}, std::chrono::duration_cast<std::chrono::milliseconds>(time_point - now()));
60 QTimer::singleShot(duration, application, std::move(fn));
61 }
62
63 static rpp::schedulers::time_point now() { return rpp::schedulers::clock_type::now(); }
64 private:
66 };
67
68public:
69 static auto create_worker(const rpp::subscription_base& sub = {})
70 {
72 }
73};
74} // namespace rppqt::schedulers
Definition: worker.hpp:31
Definition: worker.hpp:60
Base subscription implementation used as base class/interface and core implementation for derrived su...
Definition: subscription_base.hpp:25
bool is_subscribed() const
indicates current status of subscription
Definition: subscription_base.hpp:51
Schedule provided schedulables to main GUI QT thread (where QApplication placed)
Definition: main_thread_scheduler.hpp:31
Definition: constraints.hpp:22
Definition: exceptions.hpp:18