Android: pass function reference to AsyncTask

后端 未结 3 538
温柔的废话
温柔的废话 2020-12-08 05:07

I\'m new to android and very used to web developing. in javascript when you want to perform an asynchronous task you pass a function as an argument (a callback):

<         


        
相关标签:
3条回答
  • 2020-12-08 05:47

    in Kotlin

    Firstly, create class AsyncTaskHelper as below.

    class AsyncTaskHelper() : AsyncTask<Callable<Void>, Void, Boolean>() {
    
        var taskListener: AsyncListener? = null
    
        override fun doInBackground(vararg params: Callable<Void>?): Boolean {
            params.forEach {
                it?.call()
            }
            return true
        }
    
        override fun onPreExecute() {
            super.onPreExecute()
        }
    
        override fun onPostExecute(result: Boolean?) {
            super.onPostExecute(result)
            taskListener?.onFinished(result as Any)
        }
    
    }
    
    interface AsyncListener {
        fun onFinished(obj: Any)
    }
    

    the code below you can use when you want to use async task.

        AsyncTaskHelper().let {
            it.execute(Callable<Void> {
                    //this area is the process do you want to do it in background
                    // dosomething()
                    }
                }
                null
            })
            it.taskListener = object : AsyncListener{
                override fun onFinished(obj: Any) {
                    // this area is for the process will want do after finish dosomething() from Callable<Void> callback
    
    
                }
    
            }
    

    From the code above. if you want to separate your process to several task. you can do as this code below.

    AsyncTaskHelper().let {
                it.execute(Callable<Void> {
                    // task 1 do in background
                    null
                },Callable<Void>{
                    // task 2 do in background
                    null
                },Callable<Void>{
                    // task 3 do in background
                    null
                })
    
                it.taskListener = object : AsyncListener {
                    override fun onFinished(obj: Any) {
                        // when task1,task2,task3 has been finished . it will do in this area
                    }
    
                }
            }
    
    0 讨论(0)
  • 2020-12-08 05:57

    Yes the concept of callbacks also very much exists in Java. In Java you define a callback like this:

    public interface TaskListener {
        public void onFinished(String result);
    }
    

    One would often nest these kind of listener definitions inside the AsyncTask like this:

    public class ExampleTask extends AsyncTask<Void, Void, String> {
    
        public interface TaskListener {
            public void onFinished(String result);
        }
    
        ...
    }
    

    And a complete implementation of the callback in the AsyncTask would look like this:

    public class ExampleTask extends AsyncTask<Void, Void, String> {
    
        public interface TaskListener {
            public void onFinished(String result);
        }
    
        // This is the reference to the associated listener
        private final TaskListener taskListener;
    
        public ExampleTask(TaskListener listener) {
            // The listener reference is passed in through the constructor
            this.taskListener = listener;
        }
    
        @Override
        protected String doInBackground(Void... params) {
            return doSomething();
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
    
            // In onPostExecute we check if the listener is valid
            if(this.taskListener != null) {
    
                // And if it is we call the callback function on it.
                this.taskListener.onFinished(result);
            }
        }
    }
    

    onPostExecute() is called as soon as the background task finishes. You can use the whole thing like this:

    ExampleTask task = new ExampleTask(new ExampleTask.TaskListener() {
        @Override
        public void onFinished(String result) {
            // Do Something after the task has finished
        }
    });
    
    task.execute();
    

    Or you can define the TaskListener completely separately like this:

    ExampleTask.TaskListener listener = new ExampleTask.TaskListener() {
        @Override
        public void onFinished(String result) {
            // Do Something after the task has finished
        }
    };
    
    ExampleTask task = new ExampleTask(listener);    
    task.execute();
    

    Or you can subclass TaskListener like this:

    public class ExampleTaskListener implements TaskListener {
    
        @Override
        public void onFinished(String result) {
    
        }
    }
    

    And then use it like this:

    ExampleTask task = new ExampleTask(new ExampleTaskListener());    
    task.execute();
    

    You can of course just override the onPostExecute() method of the AsyncTask, but that is not recommended and in most cases actually pretty bad practice. For example you could do this:

    ExampleTask task = new ExampleTask() {
        @Override
        public void onPostExecute(String result) {
            super.onPostExecute(result);
    
            // Your code goes here
        }
    };
    

    This will work just as well as the implementation above with a separate listener interface, but there are a few problems with this:

    First and foremost you can actually break the ExampleTask all together. It all comes down to the super.onPostExecute() call above. If you as a developer override onPostExecute() like above and forget to include the super call or simply delete it for whatever reason that the original onPostExecute() method in the ExampleTask will not be called anymore. For example the whole listener implementation with the TaskListener would suddenly not work anymore since the call to the callback is implemented in onPostExecute(). You can also break the TaskListener in many other ways by unknowingly or unwittingly influencing the state of the ExampleTask so it won't work anymore.

    If you look at what's actually happening when you override a method like this than it becomes much more clear what's going on. By overriding onPostExecute() you are creating a new subclass of ExampleTask. It would be the exact same thing as doing this:

    public class AnotherExampleTask extends ExampleTask {
    
        @Override
        public void onPostExecute(String result) {
            super.onPostExecute(result);
    
            // Your code goes here
        }
    }
    

    All this is just hidden behind a language feature called anonymous classes. Suddenly overriding a method like this doesn't seem so clean and quick anymore does it?

    To summarise:

    • Overriding a method like this actually creates a new subclass. You are not just adding a callback, you are modifying how this class works and can unknowingly break oh so many things.
    • Debugging errors like this can be much more than just a pain in the a**. Because suddenly ExampleTask could throw Exceptions or simply not work anymore for no apparent reason, because you never actually modified its code.
    • Each class has to provide listener implementations at places where it is appropriate and intended. Sure you can just add them later on by overriding onPostExecute() but that is always very dangerous. Even @flup with his 13k reputation has forgotten to include the super.onPostExecute() call in his answer, imagine what some other not as experienced developer might do!
    • A little abstraction never hurt anybody. Writing specific listeners might be slightly more code, but it is a much better solution. The code will be cleaner, more readable and a lot more maintainable. Using shortcuts like overriding onPostExecute() essentially sacrifices code quality for a little bit convenience. That is never a good idea an will just cause problems in the long run.
    0 讨论(0)
  • 2020-12-08 06:02

    In Java, functions are less of a first class citizen than in JavaScript. The AsyncTask provides the callback as a method in the class, which you should override.

    See Make an HTTP request with android for a subclass of AsyncTask with an implementation of the doInBackground which makes a web request.

    If you want to do multiple HTTP requests with different callbacks, you can override RequestTask and implement onPostExecute with the different callback implementations. You can use an anonymous class to simulate the closure a JavaScript callback commonly uses:

    new RequestTask(){
        @Override
        public void onPostExecute(String result) {
            // Implementation has read only access to 
            // final variables in calling scope. 
        }
    }.execute("http://stackoverflow.com");
    

    As Xaver shows, you can also create a full-blown interface for the listener. This seems only useful to me if you wish to implement a couple default onPostExecute functions and pick one of these default implementations for a particular call.

    0 讨论(0)
提交回复
热议问题