Skip to content

Instantly share code, notes, and snippets.

@nevyn
Forked from anonymous/ExampleUsage.m
Created June 3, 2012 23:36
Show Gist options
  • Save nevyn/2865424 to your computer and use it in GitHub Desktop.
Save nevyn/2865424 to your computer and use it in GitHub Desktop.
Testing RAC by writing a socket abstraction on top of it with AsyncSocket
[[[TCRACSocket connectTo:@"localhost" port:1236] selectMany:^id<RACSubscribable>(id x) {
return [x lines];
}] subscribeNext:^(id x) {
self.text.text = x;
} error:^(NSError *error) {
NSLog(@"Failure: %@", error);
exit(0);
}];
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <AsyncSocket.h>
@interface TCRACSocket : NSObject
+(RACSubscribable*)connectTo:(NSString*)host port:(int)port;
@property(strong,readonly) AsyncSocket *sock;
-(RACSubscribable*)lines;
@end
#import "TCRACSocket.h"
#import <AsyncSocket.h>
@interface TCRACSocket ()
@property(strong,readwrite) AsyncSocket *sock;
@property(strong) id<RACSubscriber> sub;
@end
@implementation TCRACSocket {
NSMutableArray *_readers;
}
+(RACSubscribable*)connectTo:(NSString*)host port:(int)port;
{
return [RACSubscribable createSubscribable:^RACDisposable *(id<RACSubscriber> subscriber) {
TCRACSocket *wrapper = [TCRACSocket new];
NSError *err = nil;
wrapper.sub = subscriber;
if(![wrapper.sock connectToHost:host onPort:port error:&err])
[subscriber sendError:err];
return nil;
}];
}
-(id)init;
{
if (!(self = [super init]))
return nil;
_sock = [[AsyncSocket alloc] initWithDelegate:self];
return self;
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err;
{
[_sub sendError:err];
for(id<RACSubscriber> sub in _readers)
[sub sendError:err];
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port;
{
[_sub sendNext:self];
[_sub sendCompleted];
[self.sock readDataToData:[AsyncSocket LFData] withTimeout:-1 tag:0];
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
for(id<RACSubscriber> sub in _readers)
[sub sendNext:s];
[self.sock readDataToData:[AsyncSocket LFData] withTimeout:-1 tag:0];
}
-(RACSubscribable*)lines;
{
return [RACSubscribable createSubscribable:^RACDisposable *(id<RACSubscriber> subscriber) {
if (!_readers) {
_readers = [NSMutableArray new];
}
[_readers addObject:subscriber];
return [RACDisposable disposableWithBlock:^{
[_readers removeObject:subscriber];
if (_readers.count == 0) {
_readers = nil;
}
}];
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment