ReactivePlusPlus
ReactiveX implementation for C++20
Loading...
Searching...
No Matches
filter.hpp
1// ReactivePlusPlus library
2//
3// Copyright Aleksey Loginov 2023 - 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 <rpp/operators/fwd.hpp>
14
15#include <rpp/defs.hpp>
16#include <rpp/operators/details/strategy.hpp>
17
18#include <type_traits>
19
20namespace rpp::operators::details
21{
22 template<rpp::constraint::observer TObserver, rpp::constraint::decayed_type Fn>
24 {
25 static constexpr auto preferred_disposables_mode = rpp::details::observers::disposables_mode::None;
26
27 RPP_NO_UNIQUE_ADDRESS TObserver observer;
28 RPP_NO_UNIQUE_ADDRESS Fn fn;
29
30 template<typename T>
31 void on_next(T&& v) const
32 {
33 if (fn(rpp::utils::as_const(v)))
34 observer.on_next(std::forward<T>(v));
35 }
36
37 void on_error(const std::exception_ptr& err) const { observer.on_error(err); }
38
39 void on_completed() const { observer.on_completed(); }
40
41 void set_upstream(const disposable_wrapper& d) { observer.set_upstream(d); }
42
43 bool is_disposed() const { return observer.is_disposed(); }
44 };
45
46 template<rpp::constraint::decayed_type Fn>
47 struct filter_t : lift_operator<filter_t<Fn>, Fn>
48 {
49 using lift_operator<filter_t<Fn>, Fn>::lift_operator;
50
51 template<rpp::constraint::decayed_type T>
53 {
54 static_assert(std::is_invocable_r_v<bool, Fn, T>, "Fn is not invocable with T returning bool");
55
56 using result_type = T;
57
58 template<rpp::constraint::observer_of_type<result_type> TObserver>
59 using observer_strategy = filter_observer_strategy<TObserver, Fn>;
60 };
61
62 template<rpp::details::observables::constraint::disposables_strategy Prev>
63 using updated_optimal_disposables_strategy = Prev;
64 };
65} // namespace rpp::operators::details
66
67namespace rpp::operators
68{
91 * @see https://reactivex.io/documentation/operators/filter.html
92 */
93 template<typename Fn>
94 requires (!utils::is_not_template_callable<Fn> || std::same_as<bool, std::invoke_result_t<Fn, rpp::utils::convertible_to_any>>)
95 auto filter(Fn&& predicate)
96 {
97 return details::filter_t<std::decay_t<Fn>>{std::forward<Fn>(predicate)};
98 }
99} // namespace rpp::operators
Definition function_traits.hpp:45
disposable_wrapper_impl< interface_disposable > disposable_wrapper
Wrapper to keep "simple" disposable. Specialization of rpp::disposable_wrapper_impl.
Definition fwd.hpp:34
auto filter(Fn &&predicate)
Emit only those items from an Observable that satisfies a provided predicate.
Definition filter.hpp:91
Definition filter.hpp:48