2

newbie on RxCPP still learning...

I have a vector of items that is being modified continously by some thread. I want to be able to subscribe to this vector overtime and call onNext whenever something gets pushed.

void updateVec(std::vector<int> & v)
{
    v.push_back(1);
    v.push_back(2);
    ...
}

In my main I have something like this:

int main()
{
    std::vector<int> vec{};
    
    auto values = rxcpp::observable<>::iterate(vec);

    auto t1 = std::thread(updateVec, std::ref(vec));

    values.subscribe([](int v)
        { std::printf("OnNext-> value: %d \n", v); }, []() { std::cout << "OnCompleted" << std::endl; });

    t1.join();
    return 0;
}

Current output is just: OnCompleted and nothing else. I was hoping whenever the vector vec gets updated in t1 thread, onNext gets called and then the output would look something like this:

OnNext-> value: 1
OnNext-> value: 2
OnNext-> value: 3
...

what is the correct way of doing this?

Xiyang Liu
  • 81
  • 5
  • use subject seems to achieve what i want, so creating a subject in the main thread, replace this vector with subject. In t1 thread update subject with values, then in main thread gets the observable then subscribe. – Xiyang Liu Sep 30 '21 at 12:22
  • Yes, a subject will work. The vector itself has unstable iterators (every push_back() can invalidate existing iterators). Iterate stores iterators and consumes all of them at subscribe(). – Kirk Shoop Sep 30 '21 at 13:32
  • 1
    @KirkShoop that make sense, noted and thanks! – Xiyang Liu Oct 02 '21 at 18:24

0 Answers0