1

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.

Amr Salah
  • 85
  • 9
  • you can use coroutines – Shalu T D Jul 06 '20 at 11:09
  • What for Java?? – Amr Salah Jul 06 '20 at 11:13
  • If you need work with streams you can use Rx or Flow (coroutines streams) else you could use coroutines. Use Rx only to change of thread is not necessary. – Manuel Mato Jul 06 '20 at 11:26
  • @ManuelMato what do you mean by working with streams, please? For example, using Java, if I want to do http request and get response should I use RxJava instead of AsyncTasks and combine with ViewModel? – Amr Salah Jul 06 '20 at 11:36
  • 1
    A stream of data is a flow of data, emitting them and you need to consume them, for example bluetooth data. If you want to fetch data from an api, you could use the coroutines using the suspend functions (under the hood are callbacks) and if you want, use livedata in the viewmodel to update the ui. So the ViewModel launch the coroutine using the IO dispatcher and then you can update the livedata using the postValue method. Coroutines are easier than Rx and the code I think is clearer than Rx. You can read and see my base project using coroutines in proandroiddev shorturl.at/coT02 – Manuel Mato Jul 06 '20 at 12:57

1 Answers1

1

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

Ezio
  • 2,837
  • 2
  • 29
  • 45