2

我需要在 rxcpp 中实现一个摄像头采样系统。我想象的方式是将 requestStream 作为参数传递并接收 responseStream

每次调用 requestSample 时,都会创建一个新的摄像头会话,当为 requestStream 调用 on_complete() 时,摄像头会话会终止

observable<ImageSample> requestSampleStream(observable<ImageRequest> requestStream$) {
  auto response$ = rxcpp::observable<>::create<ImageSample>(
  [&](rxcpp::subscriber<ImageSample> s){
    auto request_next = [&](ImageRequest imageRequest) {
      cout << "image request next" << endl;
      SampleImage vsi;
      s.on_next(vsi);
    };

    auto request_completed = [&] {
      cout << "no more samples needed.. close camera" << endl;
      s.on_completed();
    };

    auto request_error = [&](std::exception_ptr e) {
      try { rethrow_exception(e); }
      catch (const exception &ex) {
        cerr << "error happened on request stream.. close the camera and send error on return stream" << endl << ex.what() << endl;
      }

      s.on_error(e);
    };

    requestStream$.subscribe(request_next,
                              request_error,
                              request_completed
    );
  });

  return response$;
}

这里的问题是,在requestStream$.subscribe(request_next..被调用的时候,我得到了一个 EXC_BAD_ACCESS

4

1 回答 1

2

s是一个本地堆栈变量,但 lambdas 正在捕获对s. 在调用 lambda 时,此引用无效。更改[&][=],这应该工作!

另一种选择是使用现有的map算法。

observable<ImageSample> requestSampleStream(observable<ImageRequest> requestStream$) {
    return requestStream$ |
        map([](ImageRequest imageRequest){
            cout << "image request next" << endl;
            SampleImage vsi;
            s.on_next(vsi);
        })
        // optional
        | tap([&](std::exception_ptr e) {
            try { rethrow_exception(e); }
            catch (const exception &ex) {
                cerr << "error happened on request stream.. close the camera and send error on return stream" << endl << ex.what() << endl;
            }
        },
        [](){
            cout << "no more samples needed.. close camera" << endl;
        })
        ;
}
于 2017-07-11T14:54:28.703 回答