I am trying to implement an observer/observable
pattern in Rx-cpp
. These is a very interesting tutorial in Rx.Net
on how someone can to this.
In this C#
example, there are specific interfaces
that we have to override:
public interface IObserver<in T>
{
void OnCompleted();
void OnError(Exception error);
void OnNext(T value);
}
public interface IObservable<out T>
{
IDisposable Subscribe(IObserver<T> observer);
}
As far as I understand, in Rx-cpp
there is not such a convenience. So, is it possible to provide me with some header example (myObservable.h
/myObserver.h
), similar to the interfaces
above, that I can use as a guidance to define the same communication pattern?
Any help is highly appreciated, Thank you!
EDIT 1:
Thanks to @zentrunix
, I am trying to make a class oriented communication. So far I have the code bellow for the observable pattern. What I want is to define a list of observers that will me attached into the observable and when an OnNext
is called these observers should be notified. However, there are missing part.
- How can I
subscribe()
on those observers (Rx::subscribers<int>
) when amyObservable::Subscribe()
functions is called. - Also how can I
unsubscribe()
. - Finally, how a corresponding
o.subscribe(onNext, onEnd);
in multipleonNext
observers will that be? Would it be possible to construct a correspondingmyObserver
class? (again inspired by here) Sorry for asking but is it meaningful such an organization? So far I was working with the architecture provided in this tutorial and this is the reason I am obsessed with this task. I found it as a way to get involved with the
RxCpp
. Any comments are highly appreciated.(Again sorry for my ignorance.)class myObservable { private: std::shared_ptr<std::list<rxcpp::subscriber<int>>> observers; public: myObservable() { observers = std::make_shared<std::list<Rx::subscriber<int>>>(); }; Rx::observable<int> Attach(std::shared_ptr<rxcpp::subscriber<int>> out) { return Rx::observable<>::create<int>([&, out]() { auto it = observers->insert(observers->end(), *out); it->add([=]() { observers->erase(it); }); }); }; void OnNext(int sendItem) { for (Rx::subscriber<int> observer : *observers) { (observer).on_next(sendItem); } } void Disposer(Rx::subscriber<int> out) { observers->erase(std::remove(observers->begin(), observers->end(), &out), observers->end()); }; };