Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do RestKit completion blocks run on the main UI thread?

My code tells me it is via [NSThread currentThread] isMainThread] and the fact that I can show a UIAlertView as well. This seems unexpected because my understanding is that requests are dispatched asynchronously.

I'd throw in some relevant code, but it's nothing special. I POST an object via the RKObjectManager and the success and failure completion blocks execute on the main UI thread (even though I am definitely doing stuff in the background after the request completes).

I'm confused.

What's going on?

like image 434
Brenden Avatar asked Dec 28 '13 01:12

Brenden


2 Answers

RKObjectManager behind the scenes creates and posts an RKObjectRequestOperation (which is essentially representation of your POST request) into NSOperationQueue to perform all the networking and mapping stuff asynchronously in the background thread.

When request is finished and response processed - default behavior is to run success or failure callbacks on the main thread. This is nice quick setup that helps you to build an app very fast and easy (and not worry about updating UI on the right thread).

You can easily change that behavior, RKObjectRequestOperation has 2 properties, successCallbackQueue and failureCallbackQueue, you can set them to be another background thread, and then when you need to change something on the UI side, just wrap that change into a block and post to main queue:

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    }];
like image 50
Alex Kurkin Avatar answered Nov 15 '22 16:11

Alex Kurkin


The reason why you want requests are dispatched asynchronously because you don't want UI Thread (which is main thread) blocked by the request. because when it blocked , your App wont react user's action , that's a bad user experience.

Then after the request is done, you want to let the user know it, so the dispatched thread must return to main thread. in your situation, that's the completion block. then you can do things like show alert on the main thread.

I hope this is the answer you want.

like image 21
johnMa Avatar answered Nov 15 '22 15:11

johnMa