Why can't my NSOperation object receive async call back? - asynchronous

I subclass NSOperation to implement my operation.Let's call it MyOperation.
In the implementation of MyOperation, I override the main function and inside it I create some async network stuff and set the delegate to self(the operation object).But the operation objects never get those delegate callbacks, why? I didn't set finished before the callback are received.
Or does NSOperation just can't do that?
I find that if I manually "start" the operation, it will work. But if I add it to a operation queue, the operation is excuted but just can't get those callbacks.

If you're setting up your callback in the main method like this:
-(void)main{
// setup
object.delegate = self
}
then your main method will continue execution, complete, and go away before the delegate has a chance to complete the callback. You either need to override the start method in NSOperation and manually handle the isFinished and isExecuting properties, or you need to figure out a way to have the delegate method get called on an object that isn't going away.
See the NSOperation class reference for full details on overriding the proper methods and KVC notifications to make it work.

Related

Is there a way that we can emit error or success manually on Future dart?

Something like SettableFuture/ListenableFuture java where we can control what to emit to the listener.
What I want to have is :
For example, I have a socket connection active.
I send(request) a message through socket in some function
The request also has its response, but it comes through onData(d) callback some where else not in this request funtion
I store the future in a key-value array after send
After the response on onData(d) I will get the future from the array and make it emit success or error appropriately
Normally you can make an asynchronous function either return a value (success) or throw an exception (either by throwing from a async function or by manually returning a Future.error).
If you have some existing Future that you don't control, you can't force it to succeed or to fail. You instead could make callers wait on a Future that you do control, and you could make your Future depend on the external one.
Completer can simplify some of that for you.

Using singleton WCSession delegate instead of instance methods

I'm experiencing a strange issue with WatchOS (but I suppose that this problem is similar with iOS and OSX).
I'm using a singleton to handle a WCSession delegate (The full code is by NatashaTheRobot, I paste here only a portion of her code, the full code is here ).
This class has a startSession function where the singleton is associated as delegate of the session:
func startSession() {
session?.delegate = self
session?.activateSession()
}
and all the delegate functions are defined inside the same class, like session:didReceiveMessage:replyHandler:
I'd like to be able to have the delegate called every time that the Watch app receives a message independently by the current InterfaceController.
I thought that a good place to achieve this goal might be the ExtensionDelegate class:
class ExtensionDelegate: NSObject, WKExtensionDelegate {
let session = WatchSessionManager.sharedManager // THE SINGLETON INSTANCE
func applicationDidFinishLaunching() {
session.startSession()
}
it seems that this code is not working and the delegate function are never called.
Then I decided to go for a less generic way and I started adding the reference to the singleton instance inside all the InterfaceController... but again it doesn't work and delegate methods are never been called.
Then, in my last attempt, I've implemented the session delegate protocol directly inside the InterfaceController code. In that case I receive the messages from the iOS app... it was working correctly (obviously only when the watch app is presenting that specific InterfaceController).
My question are: why implementing a generic singleton object doesn't work? Why I have to implement the delegate directly on the InterfaceController to make it work?
Try moving the startSession call from the ExtensionController's applicationDidFinishLaunching to its init method. The init gets called no matter which context (complication, app, glance, notification, etc) the extension is being loaded for.

return type for event in TinyOS

I'm implementing a module using nesC for TinyOS. My modules uses interface Timer<> so I have to implement the event fired of the interface Timer, it is possible to return a value inside this implementation or an event must be always void?
The return type of the Timer.fired event is defined as void and this cannot be changed. Even if the type was non-void, the returned value would be delivered to the component that signals the event, which is some system component implementing the Timer interface.
In order to get some hints on how to solve your problem, please provide more details explaining for what purpose you want to return a value from the fired event, that is, who is expected to get and process the returned value.

Flex - Parsley - Event Will Not Dispatch From Method in Result Handler

I have a Command that executes a service call. In the result handler, I am doing some logic based off the result data. If the logic meets specific criteria, I am displaying a confirmation popup. If the user clicks the continue button in the confirmation popup, I have a method that gets called, which dispatches a Parsley event. That Parsley event is not being caught. However, if I dispatch the Parsley event from inside the result method, it is being caught. Any idea why the event is not being caught when dispatching it from outside the result method?
For example...
[MessageDispatcher]
[Bindable]
public var dispatcher:Function;
I execute some service call from inside the command:
public function execute(event:SomeEvent):AsyncToken
{
return service.callService(event.type, false);
}
I now have a result handler like this:
public function result(data:Object):void
{
if (add some logic here based off data)
AlertHelper.showContinueQuestion(onSelection, "Are you sure you want to continue?");
}
If the user clicks the Continue button on the confirmation popup, it calls the onSelection method:
private function onSelection():void
{
dispatcher(new SomeEvent(SomeEvent.UPLOAD));
}
That Parsley event, SomeEvent, is not being caught. However, if I dispatch that event after the if statement, it is being caught and works fine. Any idea why it is not being caught when dispatched from outside of the result handler? I tried in other commands too, and it does the same thing.
Found this on the Spicefactory site, works as designed. I ended up updating a flag in the Model, versus dispatching an event. I then have a BindSetter listening for changes to that flag in the model. When the flag is set to true, the Parsley event is dispatched.
Command Object Lifecycle
Apart from grouping the executing method and the result handlers the DynamicCommand also introduces a special kind of lifecycle management for command objects. The creation of the object does not happen until a matching message is dispatched. It then becomes a container managed object just for the duration of the command execution. It will immediately be removed from the Context after the result or error handler have been invoked. But during its lifetime, it is a fully managed object, can have its dependencies injected, or even take part in messaging during the command execution. But that would be a rather rare case, most common usage scenario is probably the command object just receiving all the dependencies it needs to execute the command.

Best way to implement 1:1 asynchronous callbacks/events in ActionScript 3 / Flex / AIR?

I've been utilizing the command pattern in my Flex projects, with asynchronous callback routes required between:
whoever instantiated a given command object and the command object,
the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.
Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.
Currently I have done this using callback function references with specific kinds of signatures, but I was wondering if someone knew of a better (or an alternative) way?
Here's an example to illustrate my current method:
I might have a view object that spawns a DeleteObjectCommand instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say "deleteObjectSuccessHandler()" and "deleteObjectFailureHandler()" in this example) as callback function references to the command class's constructor.
Then the command object would repeat this pattern with its connection to the "data access" object.
When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its deleteObjectSuccessHandler() or deleteObjectFailureHandler() called.
I'll try one more idea:
Have your Data Access Object return their own AsyncTokens (or some other objects that encapsulate a pending call), instead of the AsyncToken that comes from the RPC call. So, in the DAO it would look something like this (this is very sketchy code):
public function deleteThing( id : String ) : DeferredResponse {
var deferredResponse : DeferredResponse = new DeferredResponse();
var asyncToken : AsyncToken = theRemoteObject.deleteThing(id);
var result : Function = function( o : Object ) : void {
deferredResponse.notifyResultListeners(o);
}
var fault : Function = function( o : Object ) : void {
deferredResponse.notifyFaultListeners(o);
}
asyncToken.addResponder(new ClosureResponder(result, fault));
return localAsyncToken;
}
The DeferredResponse and ClosureResponder classes don't exist, of course. Instead of inventing your own you could use AsyncToken instead of DeferredResponse, but the public version of AsyncToken doesn't seem to have any way of triggering the responders, so you would probably have to subclass it anyway. ClosureResponder is just an implementation of IResponder that can call a function on success or failure.
Anyway, the way the code above does it's business is that it calls an RPC service, creates an object encapsulating the pending call, returns that object, and then when the RPC returns, one of the closures result or fault gets called, and since they still have references to the scope as it was when the RPC call was made, they can trigger the methods on the pending call/deferred response.
In the command it would look something like this:
public function execute( ) : void {
var deferredResponse : DeferredResponse = dao.deleteThing("3");
deferredResponse.addEventListener(ResultEvent.RESULT, onResult);
deferredResponse.addEventListener(FaultEvent.FAULT, onFault);
}
or, you could repeat the pattern, having the execute method return a deferred response of its own that would get triggered when the deferred response that the command gets from the DAO is triggered.
But. I don't think this is particularly pretty. You could probably do something nicer, less complex and less entangled by using one of the many application frameworks that exist to solve more or less exactly this kind of problem. My suggestion would be Mate.
Many of the Flex RPC classes, like RemoteObject, HTTPService, etc. return AsyncTokens when you call them. It sounds like this is what you're after. Basically the AsyncToken encapsulates the pending call, making it possible to register callbacks (in the form of IResponder instances) to a specific call.
In the case of HTTPService, when you call send() an AsyncToken is returned, and you can use this object to track the specific call, unlike the ResultEvent.RESULT, which gets triggered regardless of which call it is (and calls can easily come in in a different order than they were sent).
The AbstractCollection is the best way to deal with Persistent Objects in Flex / AIR. The GenericDAO provides the answer.
DAO is the Object which manages to perform CRUD Operation and other Common
Operations to be done over a ValueObject ( known as Pojo in Java ).
GenericDAO is a reusable DAO class which can be used generically.
Goal:
In JAVA IBM GenericDAO, to add a new DAO, the steps to be done is simply,
Add a valueobject (pojo).
Add a hbm.xml mapping file for the valueobject.
Add the 10-line Spring configuration file for the DAO.
Similarly, in AS3 Project Swiz DAO. We want to attain a similar feet of achievement.
Client Side GenericDAO model:
As we were working on a Client Side language, also we should be managing a persistent object Collection (for every valueObject) .
Usage:
Source:
http://github.com/nsdevaraj/SwizDAO

Resources