Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveCocoa - Changing side effects into signals

In my application I have a signal which triggers some asynchronous network activity via flattenMap. I want to display a loading indicator while the network activity is in progress.

My current solution works just fine:

  [[[[self.signInButton
    rac_signalForControlEvents:UIControlEventTouchUpInside]
    doNext:^(id x) {
      // show the loading indicator as a side-effect
      self.loadingIndicator.hidden = NO;
    }]
    flattenMap:^id(id x) {
      return [self doSomethingAsync];
    }]
    subscribeNext:^(NSNumber *result) {
      // hide the indicator again
      self.loadingIndicator.hidden = YES;
      // do something with the results
    }];

This works, however I would like to change the above code so that the hidden property of the loading indicator can be set via a signal.

Is this possible?

Elsewhere in my app I have more complex requirements where the visibility of an element depends on a few different 'events', being able to compose these via signals would be much better.

like image 394
ColinE Avatar asked Dec 02 '22 20:12

ColinE


1 Answers

RACCommand is tailor-built for exactly this use case, and will usually result in dramatically simpler code than the alternatives:

@weakify(self);

RACCommand *signInCommand = [[RACCommand alloc] initWithSignalBlock:^(id _) {
    @strongify(self);
    return [self doSomethingAsync];
}];

self.signInButton.rac_command = signInCommand;

// Show the loading indicator while signing in.
RAC(self.loadingIndicator, hidden) = [signInCommand.executing not];
like image 182
Justin Spahr-Summers Avatar answered Dec 30 '22 22:12

Justin Spahr-Summers