1 /// A minimalistic library providing eventing-related structures. 2 module subscribed; 3 4 /// <a href="./event.html">Go to the docs for the Event struct.</a> 5 public import subscribed.event; 6 7 /// <a href="./event_machine.html">Go to the docs for the EventMachine struct.</a> 8 public import subscribed.event_machine; 9 10 /// <a href="./mediator.html">Go to the docs for the Mediator struct.</a> 11 public import subscribed.mediator; 12 13 /// 14 unittest 15 { 16 // Create and instantiate a simple finite-state machine structure. 17 enum SimpleState { running, stopped } 18 alias SimpleMachine = EventMachine!SimpleState; 19 SimpleMachine machine; 20 21 // Create and instantiate a simple mediator. 22 enum SimpleEvent { reset, increment } 23 alias SimpleMediator = Mediator!( 24 SimpleEvent.reset, void delegate(), 25 SimpleEvent.increment, void delegate(int) 26 ); 27 SimpleMediator mediator; 28 29 // Initialize a counter 30 int counter; 31 32 // Bind some events to the mediator. 33 mediator.on!(SimpleEvent.reset)(() { 34 counter = 0; 35 }); 36 37 mediator.on!(SimpleEvent.increment)((int amount) { 38 counter += amount; 39 }); 40 41 // Make sure nothing happens while the machine is not running. 42 // The listeners are only ran if the beforeEach hooks all return true. 43 mediator.beforeEach ~= (SimpleEvent channelName) { 44 return channelName == SimpleEvent.reset || machine.state == SimpleState.running; 45 }; 46 47 // Bind some events to the machine state changes. 48 machine.on!(SimpleState.stopped)(() { 49 mediator.emit!(SimpleEvent.reset); 50 }); 51 52 // Experiment with different operations. 53 machine.go!(SimpleState.running)(); 54 mediator.emit!(SimpleEvent.increment)(5); 55 mediator.emit!(SimpleEvent.increment)(3); 56 57 assert(counter == 8, "The counter has not incremented"); 58 59 machine.go!(SimpleState.stopped)(); 60 assert(counter == 0, "The counter was not reset by the machine"); 61 62 mediator.emit!(SimpleEvent.increment)(3); 63 assert(counter == 0, "The counter has incremented despite the machine being stopped"); 64 }