简体   繁体   中英

ReactiveCocoa, Serialize network requests without fire & forget

I am trying to implement code, so I can serialize network requests, basically, the next request should start only after the first one is done. I also want to subscribe to these requests, so I can handle errors. The code looks like follows:

- (RACSignal * ) sendRequest: (Request *) request{

  [[[RACSignal return:nil
  deliverOn: [RACScheduler scheduler]
  mapReplace: [self.network sendRequest]]; // A different thread is spawned to execute the request

}

and it is called as:

[self sendRequest:request
 subscribeNext: ^(id x) {
      NSLog(@"Request has been sent");
 }];

Note that sendRequest can be called from multiple threads in parallel, so the requests need to be queued.

Putting the requests on the same scheduler, didn't work, as the send happens on another thread, and the next request gets picked up, before the previous is finished. I also looked at using RACSubject that can help in buffering the requests, but it is good for fire and forget.

I was able to achieve the above using the concat command, therefore it is something like:

- (RACSignal * ) sendRequest: (Request *) request subscriber:(id<RACSubscriber>) subscriber{

  [[[RACSignal return:nil
  deliverOn: [RACScheduler scheduler]
  flattenMap:^RACStream *(id value) {
      [self.network sendRequest]]; // A different thread is spawned to execute the request
   }]
   doNext: ^(id x) {
   [subscriber sendNext];
 }

[[self sendRequest:request
 concat]
 subscribeNext: ^(id x) {
  NSLog(@"Request has been sent");
 }];

It turns out that an NSOperationQueue is unavoidable.

I have made RACSerialCommand to serialize the command execution. It has an interface similar to RACCommand, but with built-in NSOperationQueue to serialize the executions.

Feel free to try it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM