Indirect code execution flow

Khamis, 12 September 2013, 12:32 pm0

Intro: we have an Android app, with typical main and detail window structure.

Let’s see this situation: when user tap a button on main window and then open a detail window, later when user closes the detail window, it needs to update the main window UI.

Here, we have two method of how to update the UI – proactive / direct way, or passive / indirect way.

First, there are several point during detail window closing process, which we can run the function to update the main window UI.

  • when user press back button on detail window
  • when detail window close event
  • when main window resumed

Direct way – when running the function to update main window UI during the 1st and 2nd point above.

// in detail window class

detailWindow.addEventListener('androidback', function() {

// or

detailWindow.addEventListener('close', function() {

Some disadvantages for this method:

  • detail window need to keep a reference to main window.
  • if updateUI() function take some time, then closing detail window will be delayed

Therefore, to ensure responsiveness of the app, we need to utilize indirect way of executing the code. When main window resume, we run the code to update the UI. But, what if we need to update the UI only when user close the detail window? Here, we need a state variable (variable that keeps track of a state).

// in main window class

var detailWindowOpened = false;
btn.addEventListener('click', function() {
	detailWindowOpened = true;;

detailWindowOpened is the state variable, it tracks whether detail window has been opened or not.

// in main window class

mainWindow.activity.addEventListener('resume', function() {
	if (detailWindowOpened) {
		detailWindowOpened = false;

Then, when main window resume, it will automatically update its UI. So here, we don’t need to keep a reference of main window inside detail window class, and closing detail window won’t be delayed.

Tulis komen: