Skip to content

Instantly share code, notes, and snippets.

@MikeBild
Last active December 19, 2015 16:19
Show Gist options
  • Save MikeBild/5982731 to your computer and use it in GitHub Desktop.
Save MikeBild/5982731 to your computer and use it in GitHub Desktop.
simple Event-Aggregator using ReactiveCocoa
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
@interface EventAggregator : NSObject {
RACSubject *subject;
RACSignal *stream;
}
- (void) subscribe:(Class) type :(void (^)(id event))handler;
- (void) send:(id)event;
@end
#import "EventAggregator.h"
@implementation EventAggregator
- (id) init
{
self = [super init];
subject = [RACSubject subject];
RACMulticastConnection *connection = [subject publish];
stream = connection.signal;
[connection connect];
return self;
}
-(void) subscribe:(Class)type :(void (^)(id))handler{
RACSignal *filtered = [stream filter:^BOOL(id value) {
return [value isMemberOfClass:type];
}];
[filtered subscribeNext:handler];
}
- (void) send:(id)event
{
[subject sendNext:event];
}
@end
@implementation MySampleAppDelegate
+(EventAggregator*) ea
{
static EventAggregator* eventAggregator = nil;
if (eventAggregator == nil)
{
eventAggregator = [[EventAggregator alloc]init];
}
return eventAggregator;
}
void (^DateEventHandler)(DateEvent*) = ^(DateEvent *event){
NSLog(@"Date Event :%@", event.date);
};
- (void)viewDidLoad
{
[MySampleAppDelegate.ea subscribe:[DateEvent class] :DateEventHandler];
[MySampleAppDelegate.ea subscribe:[NameEvent class] :^(NameEvent *event) { NSLog(@"Name Event :%@", event.name); }];
[MySampleAppDelegate.ea send: [[DateEvent alloc]initWithName:[NSDate new]] ]; //send DateEvent
[MySampleAppDelegate.ea send: [[NameEvent alloc]initWithName:@"Demo Event"] ]; //send NameEvent
[MySampleAppDelegate.ea send: [[NoneEvent alloc]init] ]; //sample of non attached handler
[MySampleAppDelegate.ea send: [[DateEvent alloc]initWithName:[NSDate new]] ];
[MySampleAppDelegate.ea send: [[NameEvent alloc]initWithName:@"Demo Event 2"] ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment