Search code examples
c++reactive-programmingrxcpp

Rxcpp: How can I replicate the OfType operator?


I have class:

class base_event;

Several classes derive from it:

class event_1 : base_event;
class event_2 : base_event; 

I have an observable:

observable<base_event> o;

I would like to subscribe to o and get event_1 and event_2 seperately.

o.of_type(event_1).subscribe([](event_1& e){});
o.of_type(event_2).subscribe([](event_2& e){});

Is there a way to create the of_type operator like this?


Solution

  • One way to express of_type is to use

    o.filter([](const shared_ptr<base_event>& be){ 
      return dynamic_cast<event_1*>(be.get()) != nullptr;
    })
    .map([](const shared_ptr<base_event>& be){
      return static_pointer_cast<event_1>(be);
    })
    
    

    Another is to use

    .map([](const shared_ptr<base_event>& be){
      auto event = dynamic_pointer_cast<event_1>(be);
      if (event == nullptr) { return empty<event_1>().as_dynamic();}
      return just<event_1>(event).as_dynamic();
    })
    .concat()
    

    I prefer the first one.