简体   繁体   English

创建您可以在RxCpp中取消订阅的Observable

[英]Create an Observable you can unsubscribe from in RxCpp

I'm porting some code from C# that heavily relies on Rx, and I have difficulties finding C++ equivalents to some of the most used C# methods. 我正在从C#移植一些严重依赖Rx的代码,并且很难找到与某些最常用的C#方法等效的C ++。

In particular, I want to create an observable from the subscription/unsubscription logic. 特别是,我想根据订阅/取消订阅逻辑创建一个可观察的对象。 In C#, I use the Observable.Create<TSource> Method (Func<IObserver<TSource>, Action>) override to create an observable. 在C#中,我使用Observable.Create<TSource> Method (Func<IObserver<TSource>, Action>)重写来创建一个可观察对象。 For instance 例如

var observable = Observable.Create<int>(observer =>
{
    observers.Add(observer);
    return () =>
    {
        observers.Remove(observer)
    };
});

Is it possible to do the same with RxCpp ? 是否可以用RxCpp做同样的事情 I think the answer lies in the rx::observable<>::create(OnSubscribe os) method, but I can't figure out how to use it to "register" an unsubscription lambda. 我认为答案在于rx::observable<>::create(OnSubscribe os)方法,但是我不知道如何使用它来“注册”取消订阅的lambda。

In RxCpp and RxJava .subscribe() takes a subscriber. 在RxCpp和RxJava中,.subscribe()需要一个订阅者。 A subscriber is a subscription and an observer bound together. 订户是绑定在一起的订阅和观察者。

In RxCpp your example might look like this: 在RxCpp中,您的示例可能如下所示:

std::shared_ptr<std::list<rxcpp::subscriber<int>>> observers(new std::list<rxcpp::subscriber<int>>());

auto observable = rxcpp::observable<>::create<int>([=](rxcpp::subscriber<int> out){
    auto it = observers->insert(observers->end(), out);
    it->add([=](){
        observers->erase(it);
    });
});

NOTE: rxcpp::subscriber<int> is a type-forgetter that hides the type of the observer. 注意: rxcpp::subscriber<int>是一个隐藏类型的观察者。 This allows it to be stored in a collection, but introduces virtual functions for on_next, on_error and on_completed. 这样可以将其存储在一个集合中,但是引入了on_next,on_error和on_completed的虚函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM