Search code examples
androidmultithreadingandroid-asynctaskbackground-processasynctaskloader

What do you use for long running tasks since Loaders and AsyncTask have been deprecated?


Loaders and AsyncTask were really easy to use and helpful classes for long running operations like performing network http requests, but since they are deprecated, I couldn't find an alternative. I know that I may use LiveData + ViewModel as Google suggests but they are not doing tasks in a separate thread, so what can we use besides them? RxJava? or sth else? (regardless of manually creating Threads and Executors)

*I use Java.


Solution

  • For performing network requests, the network library that you are using should handle that. All network SDKs (Okhttp, Retrofit) handles the background processing, you don't have to worry.

    For other background processes or if you are using your own code to make the HTTP calls like HttpUrlConnection etc, you have a couple of options.

    1. Coroutines. If your project is in Java, that won't be a problem because Java and Kotlin are interoperable.

    2. ExecutorService: Provides a bunch of useful APIs to push a task into the background and then you can use a MainThread Looper to send the data back from background thread to UI.

    3. Handler threads and Intent service: They are standard android APIs which are made for background processing only.

    Reference: https://developer.android.com/guide/background