Issue
I made a static class (NetworkUtils.java
) with a few static AsyncTasks, each sending some data to server and retrieving a response.
It is working great (in a test environment) and it made the code very clean in the Activities:
NetworkUtils.SomeNetworkingTaskCallbackInterface callbacks =
new NetworkUtils.SomeNetworkingTaskCallbackInterface() {
@Override
public void onFinished(String result) {
}
@Override
public void onFailed() {
}
};
NetworkUtils.SomeNetworkingTask task = new NetworkUtils.SomeNetworkingTask(callbacks);
task.execute();
Now I am doing a little extra research if there is anything wrong with this approach. I've seen a lot of use-cases of nested static AsyncTasks, but I need them completely decoupled and modular, that's why I put them into a separate static class. I can't think of any downside. Can someone more experienced weigh in?
Solution
The only disadvantages I can think about is that you won't have any access to non static members of the parent class. If for example, your static Async Task
object had an Activity
parent class you wouldn't be able to call methods that require a context
. That means you won't be able to start services, activities or broadcast events from the Async Task
.
However, you could simply pass a context object to the static class to solve that. But then what happens when your Async Task
takes long and your activity gets destroyed before it's onFinish
is called? You're get an error as your context object is from a destroyed activity.
Answered By - Niza Siwale
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.