summaryrefslogtreecommitdiff
path: root/Rx/v2/src/rxcpp/sources/rx-create.hpp
blob: 95b9533766483043a06a1f865715293535120055 (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
// 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_CREATE_HPP)
#define RXCPP_SOURCES_RX_CREATE_HPP

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

/*! \file rx-create.hpp

    \brief Returns an observable that executes the specified function when a subscriber subscribes to it.

    \tparam T  the type of the items that this observable emits
    \tparam OnSubscribe  the type of OnSubscribe handler function

    \param  os  OnSubscribe event handler

    \return  Observable that executes the specified function when a Subscriber subscribes to it.

    \sample
    \snippet create.cpp Create sample
    \snippet output.txt Create sample

    \warning
    It is good practice to check the observer's is_subscribed state from within the function you pass to create
    so that your observable can stop emitting items or doing expensive calculations when there is no longer an interested observer.

    \badcode
    \snippet create.cpp Create bad code
    \snippet output.txt Create bad code

    \goodcode
    \snippet create.cpp Create good code
    \snippet output.txt Create good code

    \warning
    It is good practice to use operators like observable::take to control lifetime rather than use the subscription explicitly.

    \goodcode
    \snippet create.cpp Create great code
    \snippet output.txt Create great code
*/

namespace rxcpp {

namespace sources {

namespace detail {

template<class T, class OnSubscribe>
struct create : public source_base<T>
{
    typedef create<T, OnSubscribe> this_type;

    typedef rxu::decay_t<OnSubscribe> on_subscribe_type;

    on_subscribe_type on_subscribe_function;

    create(on_subscribe_type os)
        : on_subscribe_function(std::move(os))
    {
    }

    template<class Subscriber>
    void on_subscribe(Subscriber o) const {

        on_exception(
            [&](){
                this->on_subscribe_function(o);
                return true;
            },
            o);
    }
};

}

/*! @copydoc rx-create.hpp
    */
template<class T, class OnSubscribe>
auto create(OnSubscribe os)
    ->      observable<T,   detail::create<T, OnSubscribe>> {
    return  observable<T,   detail::create<T, OnSubscribe>>(
                            detail::create<T, OnSubscribe>(std::move(os)));
}

}

}

#endif