Skip to content
pyricau edited this page Jan 13, 2012 · 8 revisions

Since AndroidAnnotations 1.0

Fork / Join for the poor Android dev

Let's say you want to split a background operation into two separate operations that run concurrently, and then do something on the UI thread when both are done.

Here is a simple way to implement this, thanks to @Background and @UiThread.

@EActivity
public class MyActivity extends Activity {

  static class ResultHolder {
    ResultA resultA;
    ResultB resultB;
  } 

  @UiThread
  void someForkableWork() {
    ResultHolder resultHolder = new ResultHolder();
    doStuffA(resultHolder);
    doStuffB(resultHolder);
  }

  @Background
  void doStuffA(ResultHolder resultHolder) {
    ResultA resultA = new ResultA();
    // Do some stuff
    joinWork(resultHolder, resultA, null);
  }

  @Background
  void doStuffB(ResultHolder resultHolder) {
    ResultB resultB = new ResultB();
    // Do some stuff
    joinWork(resultHolder, null, resultB);
  }

  @UiThread
  void joinWork(ResultHolder resultHolder, ResultA resultA, ResultB resultB) {
    resultHolder.resultA = resultA;
    resultHolder.resultB = resultB;

    if (resultHolder.resultA == null || resultHolder.resultB == null) {
      return;
    }

    // Do some stuff on the Ui thread with the results
  }

}

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Clone this wiki locally