Managing a bunch of NSOperation with dependencies

后端 未结 4 1409
面向向阳花
面向向阳花 2021-02-01 08:40

I\'m working on an application that create contents and send it to an existing backend. Content is a title, a picture and location. Nothing fancy.

The backend is a bit c

4条回答
  •  梦如初夏
    2021-02-01 09:02

    You can use ReactiveCocoa to accomplish this pretty easily. One of its big goals is to make this kind of composition trivial.

    If you haven't heard of ReactiveCocoa before, or are unfamiliar with it, check out the Introduction for a quick explanation.

    I'll avoid duplicating an entire framework overview here, but suffice it to say that RAC actually offers a superset of promises/futures. It allows you to compose and transform events of completely different origins (UI, network, database, KVO, notifications, etc.), which is incredibly powerful.

    To get started RACifying this code, the first and easiest thing we can do is put these separate operations into methods, and ensure that each one returns a RACSignal. This isn't strictly necessary (they could all be defined within one scope), but it makes the code more modular and readable.

    For example, let's create a couple signals corresponding to process and generateFilename:

    - (RACSignal *)processImage:(UIImage *)image {
        return [RACSignal startEagerlyWithScheduler:[RACScheduler scheduler] block:^(id subscriber) {
            // Process image before upload
    
            UIImage *processedImage = …;
            [subscriber sendNext:processedImage];
            [subscriber sendCompleted];
        }];
    }
    
    - (RACSignal *)generateFilename {
        return [RACSignal startEagerlyWithScheduler:[RACScheduler scheduler] block:^(id subscriber) {
            NSString *filename = [self generateFilename];
            [subscriber sendNext:filename];
            [subscriber sendCompleted];
        }];
    }
    

    The other operations (createEntry and uploadImageToCreatedEntry) would be very similar.

    Once we have these in place, it's very easy to compose them and express their dependencies (though the comments make it look a bit dense):

    [[[[[[self
        generateFilename]
        flattenMap:^(NSString *filename) {
            // Returns a signal representing the entry creation.
            // We assume that this will eventually send an `Entry` object.
            return [self createEntryWithFilename:filename];
        }]
        // Combine the value with that returned by `-processImage:`.
        zipWith:[self processImage:startingImage]]
        flattenMap:^(RACTuple *entryAndImage) {
            // Here, we unpack the zipped values then return a single object,
            // which is just a signal representing the upload.
            return [self uploadImage:entryAndImage[1] toCreatedEntry:entryAndImage[0]];
        }]
        // Make sure that the next code runs on the main thread.
        deliverOn:RACScheduler.mainThreadScheduler]
        subscribeError:^(NSError *error) {
            // Any errors will trickle down into this block, where we can
            // display them.
            [self presentError:error];
        } completed:^{
            // Update UI
            [SVProgressHUD showSuccessWithStatus: NSLocalizedString(@"Success!", @"Success HUD message")];
        }];
    

    Note that I renamed some of your methods so that they can accept inputs from their dependencies, giving us a more natural way to feed values from one operation to the next.

    There are huge advantages here:

    • You can read it top-down, so it's very easy to understand the order that things happen in, and where the dependencies lie.
    • It's extremely easy to move work between different threads, as evidenced by the use of -deliverOn:.
    • Any errors sent by any of those methods will automatically cancel all the rest of the work, and eventually reach the subscribeError: block for easy handling.
    • You can also compose this with other streams of events (i.e., not just operations). For example, you could set this up to trigger only when a UI signal (like a button click) fires.

    ReactiveCocoa is a huge framework, and it's unfortunately hard to distill the advantages down into a small code sample. I'd highly recommend checking out the examples for when to use ReactiveCocoa to learn more about how it can help.

提交回复
热议问题