Android completion handlers

I am an iOS developer who recently tried Android development.

On iOS, I use completion handlers in my codes.

I am wondering if there is an equivalent to this in Android development?

thanks

+4
source share
1 answer

If you need it to perform asynchronous operations, look at AsyncTask - this is the class in which you implement doInBackground, where your long operation is performed, and the onPostExecute method, where the code that is supposed to update the interface is executed.

Now, if you want to pass some special code to your AsyncTask, which will be executed after a long operation, you can:

(1) , /, :

 // Psedocode to reduce size!
 interface MyInterface {
   void doWork();
 };
 class MyAsyncTask extends AsyncTask<Void,Void,Void> {
   MyInterface oper;
   public MyAsyncTask(MyInterface op) { oper = op; }
   // ..
   public onPostExecute(Void res) {
     oper.doWork(); // you could pass results here
   }
 }
class MyActivity extends Activity implements MyInterface {
   public void doWork() {
     // ...
   }

   public void startWork() {
      // execute async on this
      new MyAsyncTask(this).execute();

      // or execute on anynomous interface implementation
      new MyAsyncTask(new MyInterface() {
         public void doWork() {
            //MyActivity.this.updateUI() ...
         }
      });
   }
};

(2) , EventBus, .

(3) , :

// This can be executed on back thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
  @Override
  public void run() {
    // do work on UI
  }
});
+2

Source: https://habr.com/ru/post/1620291/


All Articles