summaryrefslogtreecommitdiff
path: root/Rx/v2/src/rxcpp/sources/rx-defer.hpp
blob: 306b4d02a12da5566160c11455e38bdc5d03e829 (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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

#if !defined(RXCPP_SOURCES_RX_DEFER_HPP)
#define RXCPP_SOURCES_RX_DEFER_HPP

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

/*! \file rx-defer.hpp

    \brief Returns an observable that calls the specified observable factory to create an observable for each new observer that subscribes.

    \tparam ObservableFactory  the type of the observable factory

    \param  of  the observable factory function to invoke for each observer that subscribes to the resulting observable

    \return  observable whose observers' subscriptions trigger an invocation of the given observable factory function

    \sample
    \snippet defer.cpp defer sample
    \snippet output.txt defer sample
*/

namespace rxcpp {

namespace sources {

namespace detail {

template<class ObservableFactory>
struct defer_traits
{
    typedef rxu::decay_t<ObservableFactory> observable_factory_type;
    typedef decltype((*(observable_factory_type*)nullptr)()) collection_type;
    typedef typename collection_type::value_type value_type;
};

template<class ObservableFactory>
struct defer : public source_base<rxu::value_type_t<defer_traits<ObservableFactory>>>
{
    typedef defer<ObservableFactory> this_type;
    typedef defer_traits<ObservableFactory> traits;

    typedef typename traits::observable_factory_type observable_factory_type;
    typedef typename traits::collection_type collection_type;

    observable_factory_type observable_factory;

    defer(observable_factory_type of)
        : observable_factory(std::move(of))
    {
    }
    template<class Subscriber>
    void on_subscribe(Subscriber o) const {

        auto selectedCollection = on_exception(
            [this](){return this->observable_factory();},
            o);
        if (selectedCollection.empty()) {
            return;
        }

        selectedCollection->subscribe(o);
    }
};

}

/*! @copydoc rx-defer.hpp
 */
template<class ObservableFactory>
auto defer(ObservableFactory of)
    ->      observable<rxu::value_type_t<detail::defer_traits<ObservableFactory>>,    detail::defer<ObservableFactory>> {
    return  observable<rxu::value_type_t<detail::defer_traits<ObservableFactory>>,    detail::defer<ObservableFactory>>(
                                                                                      detail::defer<ObservableFactory>(std::move(of)));
}

}

}

#endif