Android AsyncTask API deprecating in Android 11

News

private WeakReference activityReference;

Good riddance that it’s deprecated, because the WeakReference was always a hack, and not a proper solution.

Now people will have the opportunity to sanitize their code.

AsyncTask

Based on this code, Progress is actually not needed, and there is a String input + MyPojo output.

This is actually quite easy to accomplish without any use of AsyncTask.

public class TaskRunner { private final Executor executor = Executors.newSingleThreadExecutor(); // change according to your requirements private final Handler handler = new Handler(Looper.getMainLooper()); public interface Callback { void onComplete(R result); } public void executeAsync(Callable callable, Callback callback) { executor.execute(() -> { final R result = callable.call(); handler.post(() -> { callback.onComplete(result); }); }); } }

How to pass in the String? Like so:

class LongRunningTask implements Callable { private final String input; public LongRunningTask(String input) { this.input = input; } @Override public MyPojo call() { // Some long running task return myPojo; } }

And

// in ViewModel taskRunner.executeAsync(new LongRunningTask(input), (data) -> { // MyActivity activity = activityReference.get(); // activity.progressBar.setVisibility(View.GONE); // populateData(activity, data) ; loadingLiveData.setValue(false); dataLiveData.setValue(data); }); // in Activity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); viewModel = ViewModelProviders.of(this).get(MyViewModel.class); viewModel.loadingLiveData.observe(this, (loading) -> { if(loading) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); } }); viewModel.dataLiveData.observe(this, (data) -> { populateData(data); }); }

This example used a single-threaded pool which is good for DB writes (or serialized network requests), but if you want something for DB reads or multiple requests, you can consider the following Executor configuration:

private static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(5, 128, 1, TimeUnit.SECONDS, new LinkedBlockingQueue());

This article originally appeared on https://stackoverflow.com/questions/58767733/android-asynctask-api-deprecating-in-android-11-what-are-the-alternatives

Leave a Reply