1#include <Core/Utils/Observable.hpp>
2#include <catch2/catch_test_macros.hpp>
21 m_hookString.notify( m_name );
24 void setBestFriendNameAndAge(
std::string name,
int age ) {
27 m_hookIntString.notify( m_bestAge, m_best );
46 void spyPeter( PeterPan& p ) {
47 p.getHook().
attach( [
this]() { m_cpt++; } );
48 p.getHookName().attachMember(
this, &Spy::addName );
49 p.getHookBest().attachMember(
this, &Spy::addBest );
67 void f2(
int a ) { m_a = a; }
68 void f3(
int a,
int b ) {
72 static void g() { m_b++; }
73 static void g2(
int b ) { m_b = b; }
81TEST_CASE(
"Core/Utils/Observable",
"[unittests][Core][Core/Utils][Observable]" ) {
82 ObservableVoid observableVoid;
83 ObservableInt observableInt;
89 SECTION(
"attach member to hook" ) {
102 SECTION(
"Spy Peter Pan" ) {
105 badGuy.spyPeter( peter );
107 peter.setName(
"PeterPan !" );
108 REQUIRE(
"PeterPan !" == badGuy.m_hisName.
back() );
109 peter.setBestFriendNameAndAge(
"Tinker Bell", 150 );
110 peter.setBestFriendNameAndAge(
"John", 11 );
111 peter.setBestFriendNameAndAge(
"Michael", 8 );
112 peter.setName(
"PeterPan" );
114 REQUIRE(
"PeterPan" == badGuy.m_hisName.
back() );
115 peter.setBestFriendNameAndAge(
"Wendy", 12 );
116 peter.setName(
"Mr. Pan" );
118 REQUIRE(
"Mr. Pan" == badGuy.m_hisName.
back() );
119 peter.setBestFriendNameAndAge(
"Wendy", 18 );
121 REQUIRE( badGuy.m_hisBests.
size() == 5 );
124 SECTION(
"observe me" ) {
130 std::bind( &A::f2, &a, std::placeholders::_1 );
133 auto& observerTarget = obf.target_type();
135 REQUIRE( obf.target_type() == observerTarget );
137 auto gid = observableVoid.
attach( A::g );
138 observableVoid.
attach( bf );
139 observableVoid.
attach( [&c]() { c++; } );
143 REQUIRE( a.m_a == 1 );
144 REQUIRE( A::m_b == 1 );
146 observableVoid.
detach( gid );
150 REQUIRE( a.m_a == 2 );
152 REQUIRE( A::m_b == 1 );
154 observableVoid.
attach( A::g );
155 observableVoid.
attach( A::g );
156 observableVoid.
attach( bf );
157 observableVoid.
attach( [&c]() { c++; } );
161 REQUIRE( a.m_a == 4 );
162 REQUIRE( A::m_b == 3 );
169 REQUIRE( a.m_a == 4 );
170 REQUIRE( A::m_b == 3 );
173 observableInt.
attach( &A::g2 );
174 observableInt.
attach( [&c](
int pc ) { c = pc; } );
176 observableInt.
notify( 5 );
179 REQUIRE( a.m_a == 5 );
180 REQUIRE( A::m_b == 5 );
182 observableInt.
notify( 6 );
185 REQUIRE( a.m_a == 6 );
186 REQUIRE( A::m_b == 6 );
188 ObservableInt test2copy;
192 observableInt.
notify( 7 );
195 REQUIRE( a.m_a == 6 );
196 REQUIRE( A::m_b == 6 );
201 REQUIRE( a.m_a == 7 );
202 REQUIRE( A::m_b == 7 );
int attach(Observer observer)
void detachAll()
Detach all observers.
void notify(Args... p) const
Notify (i.e. call) each attached observer with argument p.
void detach(int observerId)
int attachMember(T *object, void(T::*observer)(Args...))
void copyObserversTo(Observable &other) const
explicit copy of all attached observers the other Observable
T emplace_back(T... args)