3

I am using RxCpp in a model-view setting. A view update method is subscribed to an observable (via lambda capturing this). Undefined memory access would ensue if the subscription were to outlive the view instance. I do not want the subscription to keep the view alive. Therefore, I need the subscription to end deterministically on the view's destructor. This sounds like a case for RAII.

Is this ever dangerous? Is it somehow a misuse of rx? I have read to prefer take_until in similar settings. Why might that be better, and how could it be used here?

Thank you!

#include "rxcpp/rx.hpp"

class MyView : public View
{
public:
    MyView(rxcpp::observable<int> obs) : obs (obs)
    {
        sub = obs.subscribe ([this] (int i) { update(i); });
    }
    ~MyView()
    {
        sub.unsubscribe();
    }
    void update(int i)
    {
        number = i;
        repaint();
    }
private:
    rxcpp::observable<int> obs;
    rxcpp::subscription sub;
    int number;
};
Jonathan Zrake
  • 563
  • 5
  • 9

0 Answers0