정책 SDK에는 하나의 관찰자 클래스가 포함됩니다. 관찰자 멤버는 가상이며 비동기 작업에 대한 콜백을 처리하도록 재정의되어야 합니다.
비동기 작업이 완료되면 OnXxx() 결과에 해당하는 멤버 함수가 호출됩니다. 예시들은 OnLoadSuccess(), OnLoadFailure(), OnAddEngineSuccess() 및 mip::Profile::Observer에 대한 것입니다.
아래 예제에서는 SDK 샘플에서도 사용되며 원하는 콜백 동작을 구현하도록 확장할 수 있는 promise/future 패턴을 보여 줍니다.
프로필 관찰자 구현
다음 예제에서는 .에서 ProfileObserver파생된 클래스 mip::Profile::Observer 를 만들었습니다. 멤버 함수는 샘플 전체에서 사용되는 미래/약속 패턴을 사용하도록 재정의되었습니다.
참고: 아래 샘플은 부분적으로만 구현되며 관련 관찰자에 대한 재정의를 mip::ProfileEngine 포함하지 않습니다.
profile_observer.h
헤더에서는 ProfileObserver를 mip::Profile::Observer으로부터 파생한 다음, 각 멤버 함수를 재정의합니다.
class ProfileObserver final : public mip::Profile::Observer {
public:
ProfileObserver() { }
void OnLoadSuccess(const std::shared_ptr<mip::Profile>& profile, const std::shared_ptr<void>& context) override;
void OnLoadFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) override;
//TODO: Implement remaining members
};
profile_observer.cpp
구현 자체에서 각 관찰자 멤버 함수에 대해 수행할 작업을 정의합니다.
각 멤버는 두 개의 매개 변수를 허용합니다. 첫 번째는 함수에서 처리하는 클래스에 대한 공유 포인터입니다.
ProfileObserver::OnLoadSuccess은 mip::Profile을 받을 것으로 예상됩니다.
ProfileObserver::OnAddEngineSuccess 를 예상할 수 mip::ProfileEngine있습니다.
두 번째는 컨텍스트에 대한 공유 포인터입니다. 구현에서 컨텍스트는 std::promise에 대한 참조로, shared_ptr<void>으로 전달된 것입니다. 함수의 첫 번째 줄은 이것을 std::promise로 캐스팅한 후, promise이라는 이름의 객체에 저장합니다.
마침내 promise->set_value()를 설정하고 mip::Profile 개체를 전달하여 미래를 준비합니다.
#include "profile_observer.h"
#include <future>
//Called when Profile is successfully loaded
void ProfileObserver::OnLoadSuccess(const std::shared_ptr<mip::Profile>& profile, const std::shared_ptr<void>& context) {
//cast context to promise
auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::Profile>>>(context);
//set promise value to profile
promise->set_value(profile);
}
//Called when Profile fails to load
void ProfileObserver::OnLoadFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) {
auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::Profile>>>(context);
promise->set_exception(error);
}
//TODO: Implement remaining observer members
비동기 작업을 수행할 때 관찰자 구현은 설정 생성자 또는 비동기 함수 자체에 전달됩니다.