Search code examples
apache-flexactionscriptairflex4

asynchronous thumbnail generation


I created a routine for generating thumbnails and heres the basic flow:

1) get all jpg url from directory
2) iterate all the url
   2.1) load url into a bitmap using URLRequest
   2.2) resize the bitmap to small size
   2.3) encode the bitmap into jpg
   2.4) write the jpg into a file
3) update list dataprovider with thumb url and refresh

this works for 1 file but fails on 2 or more files and this is bec steps 2.1 to 2.4 is enclosed in a static function with async methods. 2.1 is async, resize is async, encode is async, each are nested thru anonymous function waiting for completion event.

by the time the next iteration reaches step 2.1, it will pass new url and the callback methods from previous iteration will use it.

Whats a better approach to this problem? do i just create a class to do step 2 and instantiate it everytime instead of static functions? i feel its kinda heavy.


Solution

  • As you said, your functions need to save their state, they need common data for all sequence of operations. This is exactly why classes were invented.

    You shall not feel sorry for using this 'heavy' approach as adobe uses it with AsyncToken and so on. If this code is not a bottleneck of your program's performance, you shall definitely use classes: it will make your code much more clear.

    However, if you feel that performance is important here, you can make your iterations start async: if maximum of started operations is achieved, then don't start new operation until one of them is finished. In that case you can create pool of such classes and reuse them.

    However, I guess in your case bitmap operations duration will be so big comparing to instantiation of simple class that you can ignore instantiation overhead).

    You can also just act as you act now, just don't start new operation until previous one is 100% complete. This is a special case of previous variant, in that case your main class serves as suggested new class, it reuses itself and maximum limit of operations is 1.