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 complicated so here is what I have to do :
- Let the user take a picture, enter a title and authorize the map to use its location
- Generate a unique identifier for the post
- Create the post on the backend
- Upload the picture
- Refresh the UI
I've used a couple of NSOperation subclasses to make this work but I'm not proud of my code, here is a sample.
NSOperation *process = [NSBlockOperation blockOperationWithBlock:^{
// Process image before upload
}];
NSOperation *filename = [[NSInvocationOperation alloc] initWithTarget: self selector: @selector(generateFilename) object: nil];
NSOperation *generateEntry = [[NSInvocationOperation alloc] initWithTarget: self selector: @selector(createEntry) object: nil];
NSOperation *uploadImage = [[NSInvocationOperation alloc] initWithTarget: self selector: @selector(uploadImageToCreatedEntry) object: nil];
NSOperation *refresh = [NSBlockOperation blockOperationWithBlock:^{
// Update UI
[SVProgressHUD showSuccessWithStatus: NSLocalizedString(@"Success!", @"Success HUD message")];
}];
[refresh addDependency: uploadImage];
[uploadImage addDependency: generateEntry];
[generateEntry addDependency: filename];
[generateEntry addDependency: process];
[[NSOperationQueue mainQueue] addOperation: refresh];
[_queue addOperations: @[uploadImage, generateEntry, filename, process] waitUntilFinished: NO];
Here are the things I don't like :
- in my createEntry: for example, I'm storing the generated filename in a property, which mees with the global scope of my class
- in the uploadImageToCreatedEntry: method, I'm using dispatch_async + dispatch_get_main_queue() to update the message in my HUD
- etc.
How would you manage such workflow ? I'd like to avoid embedding multiple completion blocks and I feel like NSOperation really is the way to go but I also feel there is a better implementation somewhere.
Thanks!
A couple of thoughts:
I would be inclined to avail myself of completion blocks because you probably only want to initiate the next operation if the previous one succeeded. You want to make sure that you properly handle errors and can easily break out of your chain of operations if one fails.
If I wanted to pass data from operation to another and didn't want to use some property of the caller's class, I would probably define my own completion block as a property of my custom operation that had a parameter which included the field that I wanted to pass from one operation to another. This assumes, though, that you're doing
NSOperation
subclassing.For example, I might have a
FilenameOperation.h
that defines an interface for my operation subclass:and if it wasn't a concurrent operation, the implementation might look like:
Clearly, if you have a concurrent operation, you'll implement all of the standard
isConcurrent
,isFinished
andisExecuting
logic, but the idea is the same. As an aside, sometimes people will dispatch those success or failures back to the main queue, so you can do that if you want, too.Regardless, this illustrates the idea of a custom property with my own completion block that passes the appropriate data. You can repeat this process for each of the relevant types of operations, you can then chain them all together, with something like:
Another approach in more complicated scenarios is to have your
NSOperation
subclass employ a technique analogous to how the standardaddDependency
method works, in whichNSOperation
sets theisReady
state based upon KVO onisFinished
on the other operation. This not only allows you to not only establish more complicated dependencies between operations, but also to pass database between them. This is probably beyond the scope of this question (and I'm already suffering from tl:dr), but let me know if you need more here.I wouldn't be too concerned that
uploadImageToCreatedEntry
is dispatching back to the main thread. In complicated designs, you might have all sorts of different queues dedicated for particular types of operations, and the fact that UI updates are added to the main queue is perfectly consistent with this mode. But instead ofdispatch_async
, I might be inclined to use theNSOperationQueue
equivalent:I wonder if you need all of these operations. For example, I have a hard time imagining that
filename
is sufficiently complicated to justify its own operation (but if you're getting the filename from some remote source, then a separate operation makes perfect sense). I'll assume that you're doing something sufficiently complicated that justifies it, but the names of those operations make me wonder, though.If you want, you might want to take a look at couchdeveloper's
RXPromise
class which uses promises to (a) control the logical relationship between separate operations; and (b) simplify the passing of data from one to the next. Mike Ash has a oldMAFuture
class which does the same thing.I'm not sure either of those are mature enough that I'd contemplate using them in my own code, but it's an interesting idea.
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
andgenerateFilename
:The other operations (
createEntry
anduploadImageToCreatedEntry
) 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):
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:
-deliverOn:
.subscribeError:
block for easy handling.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.
I'm probably totally, biased - but for a particular reason - I like @Rob's approach #6 ;)
Assuming you created appropriate wrappers for your asynchronous methods and operations which return a Promise instead of signaling the completion with a completion block, the solution looks like this:
And, if you want to cancel the whole asynchronous sequence at any tine, anywhere and no matter how far it has been proceeded:
(A small note: property
root
is not yet available in the current version of RXPromise, but its basically very simple to implement).If you still want to use NSOperation, you can rely on ProcedureKit and use the injection properties of the
Procedure
class.For each operation, specify which type it produces and inject it to the next dependent operation. You can also at the end wrap the whole process inside a
GroupProcedure
class.