我需要在rxcpp中实现一个摄像头采样系统..我想象的方式是将一个requestStream作为param传递并接收一个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
答案 0 :(得分:2)
s
是一个本地堆栈变量,但lambdas正在捕获对s
的引用。调用lambdas时,此引用无效。将[&]
更改为[=]
,这应该有效!
另一种选择是使用现有的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;
})
;
}