Question

After going through the tutorial I am trying my first exercise in Reactive Cocoa going. The goal is to have a button download something from the internet using AFNetworking and these ReactiveCocoa wrappers.

I came up with this:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = nil;
RACSignal *buttonSignal = [self.stepperButton rac_signalForControlEvents:UIControlEventTouchUpInside];
RACSignal *getSignal = [buttonSignal map:^id(UIButton *button) {
    return [manager rac_GET:@"https://farm3.staticflickr.com/2815/13668440264_e6403b3100_o_d.jpg" parameters:nil];
}];
RACSignal *latestSignal = [getSignal switchToLatest];
[latestSignal subscribeNext:^(id x) {
    NSLog(@"x: %@",x);
}];

This seems to do a couple of things that I want:

  1. It downloads the image from flickr as requested
  2. It cancels the previous request when clicking on the button too fast (switchToLatest was the key here)

But it fails on other things:

  1. I can not seem to get valid responses in my subscribeNext. x is always null.
  2. Whenever a request fails the signal goes in error state and pushing the button does not trigger any new GETs anymore.

I guess I am missing lots of things here since I am new to Reactive Cocoa but maybe there are people that are willing to give hints to get me going in the right direction?

Are there other approaches that I fail to see?

Was it helpful?

Solution

This seems to work:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = nil;
RACSignal *buttonSignal = [self.stepperButton rac_signalForControlEvents:UIControlEventTouchUpInside];
RACSignal *getSignal = [buttonSignal map:^id(UIButton *button) {
    return [[manager rac_GET:@"https://farm3.staticflickr.com/2815/13668440264_e6403b3100_o_d.jpg" parameters:nil] catch:^RACSignal *(NSError *error) {
        NSLog(@"catch %@",error);
        return [RACSignal empty];
    }];
}];
RACSignal *latestSignal = [getSignal switchToLatest];
[latestSignal subscribeNext:^(NSData *data) {
    NSLog(@"dowloaded %d bytes",data.length);
}];

Thanks Stackoverflow similar questions! Powerful stuff.

The catch should be on the rac_GET. Before I had been trying to do things with catch but on the buttonSignal pipe.

And the reason x was always null was because I did not have a serializer set up on the manager.

I thought about deleting this question, but maybe there are people that still have remarks on the solution?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top