Waiting while SWFLoader loads a swf file - apache-flex

Currently I'm working on an application (Flex) which heavily uses external SWFs.
I'd like to create a static method which takes a filename as an argument and returns SWF wrapped in some other class.
public static function getSWFWrapperFromFile(path:string):SWFWrapper {
var loader:SWFLoader = new SWFLoader();
loader.addListener(Event.COMPLETE, onLoad);
loader.load(path);
// If I create new SWFWrapper object here and try to assign it the loader.content I get null reference
}
However, with this approach I'm not able to encapsulate logic in one function, because of non-blocking load() and the need of onLoad handler. Is there possibility to force a delay after calling load method? Or mayber there is another, better way?
Thank you,
Alonzo

The display list is well-designed for asynchronous loading. You'll notice that Loader is a DisplayObject-derived class and thus can be placed directly in the display list. When its content is loaded it will be a child of the Loader. Thus, if SWFWrapper is DisplayObject-derived, you can simply do the following at the end of your code:
var wrapper:SWFWrapper = new SWFWrapper();
wrapper.addChild(loader);
return wrapper;

You need to wait until your Loader object has completed. Try adding in an event handler. Yes, the whole thing gets murky after a point of time when you have multiple loaders and and have to wait till the last one has completed. But that's the way it is if you are going to use SWFLoader.

In flash you cannot block in a method - you always have to use the onLoad handler for loading data. (The as3 execution model is single threaded, if you block in a method the rest of the program will not get executed)

Like others said, you can't do that. However, take a look at the BulkLoader AS3 library, which takes the burden of managing multiple loaders simultaneously and waiting for their completion, off your shoulder. It is well documented, and requires only a few lines to use.

Related

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.

flex mobile project : memory management

I have developed my first flex mobile application which is of TabbedViewNavigatorApplication. Application is working fine but when I test the application in "profile handler", memory usage goes on increasing as I navigate through the application. When I came to know that, I have to remove all the added eventlisteners and I have to nullify the objects which are no longer needed. When I switch between tabs , tabs are initialising again and again.
I dont know where can I remove the eventlisteners. I mean, I have written functions for each eventlisteners . Do I need to remove eventlistener when control goes to the function definition.
I have written sample code
var more:Image = new Image();
more.width = 70;
more.height=29;
more.x=10;
more.y=276;
more.source = "Assets/more button.png";
more.addEventListener(MouseEvent.CLICK, MORE_clickHandler);
mainGroup.addElement(more);
private function MORE_clickHandler(e:MouseEvent):void {
// Do I need to remove the eventlistener here
}
Also , do I need to explicitly nullify the object of Image class which I created or garbage collector will handle it. If I need to explicitly nullify it, where to do this.
Thanks
Garbage collection is an important part of any language, especially on mobile. Since mobile devices are a lot more limited than say our desktop counterparts, you need to be very careful what is being created/stored to memory. My motto is, if you don't see it, you shouldn't keep it. You can destroy views but keep their state using a view model.
To remove a view, you need to first remove it from the display list (removeElement(yourObject)), remove all event listeners, and nullify any referencing variable. If any variable still has a reference to it, it won't get garbage collected.
I recommend you read up a bit more on garbage collection as well as some neat tricks like pooling and virtualization (item renderers in a list).
You can setup an event listerener with a weak reference.
This implies that when the only reference to your object is the listener, the object itself can still be garbage collected and the listener will not keep it in memory.
The following will do the trick :
more.addEventListener(MouseEvent.CLICK, MORE_clickHandler,false, 0, true);
Another option would be to subclass the image class and let it implement an IDisposable interface, which would force you to implement a dispose() method.
Some handy resources:
http://www.intriguemedia.net/2007/09/24/when-to-use-weak-references
http://gskinner.com/blog/archives/2006/07/as3_weakly_refe.html
cheers

How to call actionscript functions inside the swf file loaded in swfLoader of my flex app?

I have a swf file sample.swf which has its actionscript class in Main.as. This Main.as has various objects declared as public in it. For instance lets consider an object myData of class MyData (in MyData.as).
I am loading this swf file in my AIR app using swfLoader. I want to know how do I access myData.func() using swfLoader.loaderInfo.content.
Thanks in advance... :)
in your init handler, it should be something like:
function myLoadHandler( e:Event )
{
MyData( e.target.content.myDataInstance ).func();
}
where myLoadHandler is the event handler for the Event.INIT event (COMPLETE is fired when all the bytes are loaded, INIT is fired after the SWF is initialized and its members are accessible), and myDataInstance is the public reference to your MyData instance inside your child SWF.
I have done this before. I can't recall the exact path to the data but a way to find out is using the debugger in flex. Add an Event.Complete event for the loader and add a breakpoint inside the complete function you call. Then add the swfLoader.loaderInfo.content to expression watch list and start drilling down to find what you are looking for. Note the path and try giving it a call in a test function.

Detect when ALL HTML page rendering has taken place

I am working with a pretty complicated .aspx page that is full of controls (Telerik, Ajax, etc.) that all expand, collapse, show, hide, etc. when the page is loaded. Since this rendering happens on the client-side and can take different lengths of time based on the users machine specs, is there a way to detect when all (or some) rendering has taken place (jQuery?) so I can then act on specific elements, knowing they are fully rendered?
JavaScript is single threaded. The time passed to setTimeout is a minimum, but not a maximum, so if you pass something like 10(ms), you essentially are saying "execute this code after all the currently running code is finished."
So, if all the controls use $(document).ready() to do their thing, all you need is:
$(document).ready(function() {
setTimeout(function() {
doStuff();
},10);
});
doStuff will be called after all the functions passed to $(document).ready have run. However, this isn't foolproof. If the controls have their own way of detecting whether the document has loaded, or do their own setTimeout(), you're in trouble. The problem is that JavaScript does not guarantee the execution order of setTimeouts. Sometimes your code may run last, other times it may run before the setTimeouts used for the animation.
One last idea: if all the animation is done using jQuery, then the effects run in a single queue. In doStuff you could add an animation of some sort with a callback and be reasonably certain that the callback would run last.
Whenever I had to wait for multiple things to be ready before proceeding, I would create an array with true/false values. Every mandatory part of the page got an event which, when it is called, updates the specific entry in the array to true. Also, it called a general function which returned true if all values in an array was true, otherwise false.
If that function finally returned true, I would proceed with the execution. It is especially useful if you have to wait for an AJAX call to end but don't want to use async = true. It also is useful if you want to start loading multiple things at once instead of one after another, since they all report ready-state to the same array.
It does however use global variables so you might need to do some optimizations. You might not want to do this approach either if you have a grudge against global variables.
You should place your code inside the jQuery $(document).ready() function. This will ensure that all elements are loaded before the code runs.
http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
I think the doc you need is:
http://docs.jquery.com/Events/load
"I can then act on specific elements, knowing they are fully rendered?"
You can use the load method (linked above) to attach to any element. So if you had a div with an id of "lastElement", you could write
$('div#lastElement).load(runThisFunction);

AS3 - How to do a synchronous load of an asynchronous call?

I have a function that loads a user object from a web service asynchronously.
I wrap this function call in another function and make it synchronous.
For example:
private function getUser():User{
var newUser:User;
var f:UserFactory = new UserFactory();
f.GetCurrent(function(u:User):void{
newUser = u;
});
return newUser;
}
UserFactory.GetCurrent looks like this:
public function GetCurrent(callback:Function):void{ }
But my understanding is there is no guarantee that when this function gets called, newUser will actually be the new user??
How do you accomplish this type of return function in Flex?
This way madness lies.
Seriously, you're better off not trying to force an asynchronous call into some kind of synchronous architecture. Learn how the event handling system works in your favour and add a handler for the result event. In fact, here's the advice straight from the flexcoders FAQ :
Q: How do I make synchronous data calls?
A: You CANNOT do synchronous calls. You MUST use the result event. No,
you can't use a loop, or setInterval or even callLater. This paradigm is
quite aggravating at first. Take a deep breath, surrender to the
inevitable, resistance is futile.
There is a generic way to handle the asynchronous nature of data service
calls called ACT (Asynchronous Call Token). Search for this in
Developing Flex Apps doc for a full description.
See my answer here:
DDD and Asynchronous Repositories
Flex and Flash Remoting is inherently asynchronous so fighting against that paradigm is going to give you a ton of trouble. Our service delegates return AsyncToken from every method and we've never had a problem with it.
If you want to ensure that the application doesn't render a new view or perform some other logic until the result/fault comes back, you could do the following:
Attach an event listener for a custom event that will invoke your "post result/fault code"
Make the async call
Handle the result/fault
Dispatch the custom event to trigger your listener from #1
Bear in mind this going to lead to a lot of annoying boilterplate code every time you make an async call. I would consider very carefully whether you really need a synchronous execution path.
You can't convert async call into sync one without something like "sleep()" function and as far as I know it is missing in AS3. And yes, it is not guaranteed that newUser would contain user name before return statement.
The AS3 port of the PureMVC framework has mechanisms for implementing synchronous operations in a Model-View-Controller context. It doesn't try to synchronize asynchronous calls, but it lets you add a synchronous application pattern for controlling them.
Here's an example implementation: PureMVC AS3 Sequential Demo.
In this example, five subcommands are run sequentially, together composing a whole command. In your example, you would implement getUser() as a command, which would call commandComplete() in the getURL() (or whatever) callback. This means the next command would be certain that the getUser() operation is finished.

Resources