Channels in ActionScript

Our example demonstrates channels, the constructs that connect concurrent goroutines to send and receive values.

package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.utils.setTimeout;
    
    public class Main extends Sprite {
        private var messages:Array = [];
        
        public function Main():void {
            sendMessage("ping");
            this.addEventListener(Event.ENTER_FRAME, checkMessages);
        }
        
        private function sendMessage(msg:String):void {
            setTimeout(function():void {
                messages.push(msg);
            }, 1000);
        }
        
        private function checkMessages(event:Event):void {
            if (messages.length > 0) {
                var msg:String = messages.shift();
                trace(msg); // equivalent to fmt.Println in the original code
            }
        }
    }
}

When we run the program, the “ping” message is successfully passed from one function execution to another via our messages array being checked in the checkMessages event handler.

By default, Flash application loops make it possible to check for messages at each frame, thus simulating the concurrent behavior.

To run this code, write it in an ActionScript file and compile it with the Adobe Flex SDK. The output will show “ping” in the console.

Next example: Channel Buffering.