Use of deferred execution method in Objective-C - objective-c

My purpose is as follows: I want to create a deferred calling method. I might need to create a block for this, but I'm not sure. Can you explain me how to create a block for this?
This is the code:
- (IBAction)buyItem:(id)sender {
BOOL purchase = ... /*call purchase method use block*/
}
In this method I make a purchase and after the purchase has completed successfully I want to get result in my variable purchase.
To be more clear:
Step 1: Call the buyItem method.
Step 2: Wait for a response to the purchase (I've omitted the actual methods for the purchase)
Step 3: After the StoreKit object return a response about the purchase, write a value into the variable purchase.
Step 4: After writing the value into purchase, my method buyItem completes execution (go to the } and release).
My question is not about StoreKit specifically (meaning the StoreKit response method - this is an example only). The purchase variable is an example, too. For this variable I will use a data model and it will change after the deferred method executes.
Thanks all!

You do need a block, but maybe a different kind than you're thinking about. You don't need a 'closure', you need a function that will block until it receives the response from the store kit/server.
You can just write a normal buyItem method, but inside you either make a synchronous call to store kit, or if that's not possible, you use threading techniques to achieve what you want. For example, you could wait on a condition variable and then signal it when the store kit call returns.
For both cases, you'll want to perform the 'buyItem' call on a thread other than the UI thread, otherwise your UI will freeze. Given that constraint (if you're even dealing with a UI), I would say this entire approach doesn't make sense. Instead, you'll want to launch the store kit call, set some indicator or spinner or something in your UI, and then when the store kit call returns, unset the spinner or whatever. Make sense?

Related

How to tell if middleware contains a Run()?

Is there any way to tell in ASP.NET Core if any given middleware will contain a Run() call which will stop the pipeline? It seems that UseMvc() is one big one, but I am not even certain about that, I just keep reading that it needs to go at the end, I assume it is because it contains a call to Run().
Perhaps there is a way to generate a visualisation of the pipeline for all middleware currently in use, showing which one contains the Run() call?
There is no sure way to tell, beyond reading documentation on each specific piece of middleware.
quoting itminus in the comments on my question:
Not only Run(), but also MapWhen() will terminate the process. Also, anyone could create a custom middleware that doesn't invoke the next delegate and then cause to a terminate.
It's the duty of middleware to determine whether there's a need to to call next. There's no built-in way to visualize the pipeline except you read the document/source code. That's because all the middlewares will be built into a single final delegate at startup time. When there's an incoming message, the final delegate will be used to process requests. As a programmer, we know what will be done by the middlewares, we know the time when it branches, and we know the time it terminates that's because we write the code. But the program won't know it until it actually runs just because the final delegate is built at startup time.

How to properly execute performFetchWithCompletionHandler with multiple blocks inside

I'm using the background fetch method performFetchWithCompletionHandler in order to update some user data. However, those processes are fairly complicated and include block statements, so they don't execute synchronously.
My concern is that I am always returning completionHandler(UIBackgroundFetchResultNewData);
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(#"Start background data fetch");
// Update data -- this method contains various blocks inside
[GETDataRequest updateUserDataWithUser: user];
// Update images -- this method contains various blocks inside
[GETImagesRequest updateUserImagesWithUser: user];
NSLog(#"Background Data Fetch completed");
completionHandler(UIBackgroundFetchResultNewData);
}
According to this post, in regards to completionHandler(UIBackgroundFetchResultNewData) the following was mentioned:
You have to call this to let iOS know what the result of your background fetch was. It uses this information to schedule future background fetches. If you neglect to do this, future background fetches may be delayed by the OS. The consequences of not calling this handler might include terminating your app altogether.
As you can see here, I am always saying it's successful whether or not it actually is. The answerer had this to say about my situation:
...you should call the completion handler only when your fetch is actually complete. Otherwise iOS will probably put your application back to sleep before the connection completes, and apps shouldn't actually be able to determine UIBackgroundFetchResultNewData versus UIBackgroundFetchResultNoData or UIBackgroundFetchResultFailed until then anyway. How do you know your connection will succeed?
Is what I'm doing ACTUALLY a problem? Will it actually cut off the updates? If it is going to produce unexpected results, what's the solution to this mess? The answer to the question I mentioned wasn't clear enough to me. I have tried using block variables to make it function as it should, but have been unsuccessful. Much appreciated.
The code you are using is meant for Background Fetch Refresh functionality, through this you can make a quick refresh to your app when its in background by mentioning the system time interval to minimum. This service is available in the delegate method performFetchWithCompletionHandler and it will last for 30 seconds. You need to manage your code accordingly to get updated result and then at end as per your result you need to call the appropriate completion handler block.
If you have the long running background task I will prefer then to use Background Fetch Services using NSURLSessions.

what is the best use of BusyIndicator?

Just want to understand the usage of busy indicator does it alternate to timeout/putting wait etc.
for example have following line of code in mainfunct()
1. busy.show();
2. callcustom(); --asynch function without callback this is calling xmlhttpRequest etc.
3. busy.hide();
4. callanothercustom(); -- asynch function without callback
now question is
does line 4 will be executed only when busy.hide() completes and
line 3 only when line 2 is completed while without busy all (2,4)
will be called inside mainfunct() without waiting line 2 to
complete...
when busy.hide() is being called is there any timer setup which
holds until line 2 finishes and then hide and call line 4.
A busyIndicator's show and hide functions only control when to display the indicator and when to hide the indicator. They have no effect what-so-ever on anything else going on in your code.
In other words your code is basically:
callcustom()
callanothercustom()
In your customcode you can still make sure that callanothercustom will be called only when it's finished by adding your own callback... I assume this is AJAX inside of it, so: jQuery ajax success callback function definition
function callcustom() {
$.ajax({
url : 'example.com',
type: 'GET',
success : callanothercustom
})
}
And then in callanothercustom you can busy.hide...
Or any other combination of business logic - it really depends on what's going on in your code.
In my opinion, the only main use case for using a busy indicator is a Long running synchronous task that's blocking UI. Let's say greater than 2 seconds long. Hopefully, these are few are far between.
If you have asynch tasks, then the UI is not blocked and user can interact. If you are relying on the results for next steps as you imply above, then you must have a callback/promise to trigger the next steps. If you want the user to be blocked until the async task is complete, then treat it as a synch task and show the Busy.
Be aware, use of Busy Indicator is now seen mostly as an anti-pattern. Its basically yelling at your user "See how slow this app is!". Sometimes you cannot avoid dead time in your app, such as fetching a large block of data to generate a view, but there are many ways to mitigate this. An example may be to -- get something on the view as fast as possible (< 1 sec), and then backfill with larger data. Just always ask yourself WHY you need this Busy, and can I work out a way to avoid it, but not leave the user wondering what the app is doing.

If I mock an object and/or stub a method in my spec, will that mock be used even though it's only called indirectly?

I am new to mocking and stubbing, but I think I have a circumstance where their use would be ideal.
In my application, when a user saves a Product, an after_save callback fires that creates Publication instances which cause the product data to be sent to certain 3rd parties via API.
I have a request spec for Product that tests my CRUD operations.
If I stub either the API methods or mock the Publication model, will those mocks/stubs be used in my spec even though they are actually called in the Product after_save callback? I'm confused about this point.
Update
I figured I would just do it like this:
Publication.any_instance.stub(:publist).and_return(true)
And do that at the beginning of my test. That way whatever instance is created would be handled. Is that how it works?
Yes that stub will do what it says and the publist method on any instance of the publication class will always return true.
Instead of putting it "at the top" though do something like.
context 'when there is a publist' do
Publication.any_instance.stub(:publist).and_return(true)
it 'should ...' do
...
end
end
then if required you can do tests without the stub, or tests where publist returns false in other context blocks and be nice and clear in the spec.

Method Interception, replace return value

We’re using Ninject.Extensions.Interception (LinFu if it matters) to do a few things and I want to know if its possible to return a value form the method being intercepted.
EG
A Call is made into one of our repository methods
Our Interceptor gets the BeforeInvoke event, we use this to look into the ASP.NET Cache to see if there is any relevant data
- Return the relevant data (this would cause the method to return immediately and NOT execute the body of the method
- Or Allow the method to run as per normal
Extra points if in the AfterInvoke method we take a peek at the data being returned and add it to the cache.
Has anybody done something similar before?
From your question I assume that you derive from SimpleInterceptor. This will not allow to return imediately. Instead you have to implement the Iinterceptor interface. You can decide to call the intercepted method by calling the Proceed method on the invocation or not.