How does Objective-C's asynchronous request model work? - iphone

I've been playing with Objective-C the past couple of weeks and have a working app that performs an async HTTP Request to pull some data from Twitter.
I come from a web application background and have become use to how Javascript handles callbacks by passing a function that is called when an XHR request is done loading. As such, I find Objective-C's model of handling async requests with delegate objects and the perfomSelector method pretty darn cool.
[callbackObj performSelector:#selector(callbackMethod:) withObject:argObj];
So my question is, what is the design of Objective-C's async model and how does it work?

All of "Cocoa Classic's" async behavior is / was implemented on top of NSRunLoop. Many of the more recent additions and updates to Cocoa are moving to Grand Central Dispatch.

Related

Why use ngrx/effects for http async calls

There are many articles out there that recommend using ngrx/effects for handling async actions such as http REST calls. Instead of using effects, why can't we just use a regular service to make the http call and then take the result of that http call and dispatch an action? Doesn't that simplify things?
You can perfectly use a regular service and then dispatch an action, like this on a component.
this.store.dispatch({
type: "SAVE_DATA",
payload: data
});
this.saveData(data) // POST request to server
.map(res => this.store.dispatch({type: "DATA_SAVED"}))
.subscribe()
#ngrx/effect just abstracts this logic away from the component. By doing this with a functional programmic aproach (pure functions), code remains very easy to test.
I really recommend reading this article, since there are many solutions to problems that abuse effects
Post
Using ngrx/effects makes life more simpler than using service to make http call and then take the result and dispatch the action. As following
Effects provide abstraction to the service layer. Our components don't need to know about the services(http) layer. Components will only dispatch actions to get things done.
As Effects are basically service, code is written once and reused multiple times.

How do you introduce reactive programming in an existing projet?

Potentially "subjective" question : what is a sweet spot for introducing reactive programming (rxjs, bacon, etc...) into an existing, "old-school- MVC-jquery" client side application ?
For example, Promises shine the most if you introduce it in the "API calls" layer of an application (and you can do it one function at a time, returning a Promise instead of accepting a callback - they, it tends to disseminate once everyone in the team gets a few benefits.)
From most of the tutorials I could read, I do not really see where rxjs would shine most. In the widgets (returning stream of events instead of having a 'listener-based' API ?)
Any experience welcome.
It is hard to say where it will shine the most…
For me, the key feature, is that it allows to describe code in more declarative way instead of writing complicated state machines(as it often happens when working with async logic).
In general, it can be quite useful for anything async for example in UI, or for API calls layer implementation as you mentioned about Promises, but better(promise is just a limited version of observable, except the fact that observable is lazy).
In case of implementing API calls layer, in comparison to promises it will have at least following benefits:
subscription to observable is cancellable(disposable) - for example, you can switch between subscriptions for api results without worrying about race conditions with previous api requests... it is as simple as results = queries.switchMap(q=>doApiCall(q))
it can return multiple values using the same interface - you can easily replace ajax call with subscription to web-socket, and you will not need to change code that is using this.
better error handing - it is quite easy with rx to do things like retrying operation n-times before throwing an error, or handling timeout.
I suggest you to watch Netflix JavaScript Talks - Async JavaScript with Reactive Extensions by Jafar Husain, there is great examples about where RxJS can be helpful. And likely it would be mostly an answer to your question.

iPhone Mobile Application and Polling / Web Service

I'm working with an iPhone developer on an application. I know very little about the iPhone. I'm writing the server-side code in Grails. I'm wondering what is available to me as far as approaches to using a RESTful JSON service with an occasional poll of the service.
From the iPhone:
Is there a way to put these calls on a background thread? when the data comes back is there a callback mechanism? Looking for some basic information on how to accomplish this on the iPhone / Objective-C.
Yes, typically you either provide a delegate that is notified when an asynchronous request has some kind of event (e.g. more data comes in, the request fails, etc.), spawn a background thread that performs synchronous requests, or pass success/failure blocks to an asynchronous request that executes them when appropriate.
But if you are working with an iPhone developer, shouldn't he be dealing with this, not you?
Have a look at NSURLConnection. It automatically puts the request on a background thread and has some callback methods that get called on its delegate.
I prefer using the ASIHttpRequest library for my integrations with RESTful rails apps. One of many advantages is the completion block:
request.completionBlock = ^{ NSLog(#"I'm finally complete!"; };
[request startAsynchronous];

Thread Vs Async call

I wanted to know the best between Spawning a Thread or making a async call using NSURLConnection class.
See the documentation.
An NSURLConnection object provides
support to perform the loading of a
URL request. The interface for
NSURLConnection is sparse, providing
only the controls to start and cancel
asynchronous loads of a URL request.
i.e. NSURLConnection only supports asynchronous loading of content. Even the sendSynchronousRequest:returningResponse:error: method is really just a wrapper around async loading that blocks until done.
That class reference has links to both the programming guide and numerous examples.

Delegation in a NSThreaded Design? (iPhone)

Im using a large amount of very small web services in my app and I have been down a couple of roads that does not scale or work as desired.
The Design approach Im thinking about:
The task for the viewController is to ask for a set of data from a general webServicesClass, this task is started in a new NSThread -> this will instantiate an object which solely retrieves the xml and returns it to the webServicesClass -> the webServicesClass now instantiates an object which solely can Parse some XML coming from this particular web service. The Parser then returns a nice Entity object to the webServiceClass. The WebserviceClass now needs to inform the viewController about this data.
The viewController implements a webServiceClassDelegate and some delegate methods to see if the web service request went as planned. e.g. -(void)aWebserviceFailed and -(void)aWebserviceSuccess.
0.5 Since the WebserviceClass is running is a different NSThread, will it be a problem calling delegate methods on the main NSThread in the parent object?
1.0 I think this design is sound as it completely incapsulates the retrieval, parsing and returning of the Entity in different classes. But, I will have to write delegation methods and implement delegation protocols on each step of the way, for each different webservice. i.e. starting from the bottom, the WebserviceClass must implement delegation methods for both the object that retrieves the XML (start, fail, success), then for the object that parses the XML(start, fail, success) and the WebserviceClass must be able to delegate each of these responses to the viewController that again must implement delegation methods from the WebserviceClass(start, fail, success).
Is there a much simpler way to do this?
I have some design pattern experience, but not from languages that uses delegation so consistently as Objective C. In AS3 or Java I would have events that could bubble up through the objects and inform whoever was listening about changes. In all the Objective example code I have read I have only seen NSNotifications (which would be the equivalent of the AS3 or Java 'Event') used 0.1% of the times.
The Design I described will give me something that scales perfectly for many web services and gives me complete control over where a potential error/exception happens, but it seems to be a lot of code to obtain this loose coupling.
1.1 Or should I fully embrace the delegation approach and get to work:)
Thanks for any pointers or help given. Im not asking for source code or the likes, more a "this is considered best practice in Objective C in the every day situation you just described" :)
I'd recommend taking a look at ASIHttpRequest(obtainable here) and NSOperation + NSOperationQueue (docs here). I don't think you should run a long-lived thread to talk to your web service all the time, unless you absolutely need a constant connection.
Basically ASIHttpRequest and NSOperation both encapsulate all of the networking and threading stuff. Operations make multi-threading on the iPhone really nice. Essentially you create an operation (through a factory or whatnot for ease of use), pop it in a queue and do something with the result.
As for what you do with the result (this applies to your original scenario too and 0.5 and 1.1) what typically happens is your operation/thread will then call a didSucceedAtGettingWhatever or didFailWithError:(NSError*) method. Delegation is pretty much the defacto way of making requests on the phone. If there are multiple delegates, then you can just use subject-observer, like you would in Java.
As for 1.0, ultimately no. What we typically do is we have an OperationDelegate and OperationTypes. Based upon which OperationType succeeded or completed, we have different logic. It's not the greatest and there are a ton of different ways of doing this, but you will have to have separate logic for separate events regardless of what you do. Whether or not that's in one method or many methods is up to you.