0

There are few techniques to execute slow code that returns some data in Android. By slow code I mean network, file, database access etc.

  1. Thread and Runnable can be used, but I found that getting produced data from a Runnable is hard/not productive.

  2. We can use Service with Broadcast, but I found that this is also not productive technique.

  3. We have nice AsyncTask class in Android.

    Is this last approach most productive way to execute slow background operations that return some data, or there is something better in Android?

Kamil
  • 13,363
  • 24
  • 88
  • 183
  • 2
    `AsyncTask` has been deprecated for a few years. "`Service` with `Broadcast`" is unrelated to threads. Reactive frameworks (RxJava, Kotlin coroutines) are the recommended approaches nowadays for general-purpose stuff. But the answer may vary depending on scenario: threading models for games will be very different than threading models for social media clients, for example. – CommonsWare Sep 19 '22 at 21:31
  • @CommonsWare Thanks. I'm trying with RxJava/RxAndroid, but I can't find learning resources suitable to my needs. Most RxJava tutorials elaborate about many operators, mappings, filters, timers, intervals and after few hours I can't find example that shows how to call a function with a parameter and get returned value on another thread... – Kamil Sep 20 '22 at 15:54
  • 1
    `Single.fromCallable({}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({}) {}`. The `fromCallable()` lambda would wrap your function call. The first `subscribe()` lambda gets your result. The second `subscribe()` lambda gets called if an exception is raised, such as from that function call. Change the two schedulers as needed based on what threads/pools you want to use. See https://stackoverflow.com/a/56209888/115145. – CommonsWare Sep 20 '22 at 16:07
  • Well, to make it more readable for learning I have created `Callable` and put it as .fromCallable() parameter and `new SingleObserver()` as parameter of .subscribe(). Now I can get my `String` result (awesome!), but now I cannot pass parameter to my background code (not awesome). – Kamil Sep 20 '22 at 17:14
  • You might consider asking a separate Stack Overflow question with a [mcve] that shows what you are trying to do and asking for help in converting it to RxJava 2 or RxJava 3 (whichever you are trying to use). – CommonsWare Sep 20 '22 at 17:25
  • @CommonsWare I did. It's here: https://stackoverflow.com/questions/73789460/how-to-use-rxjava-rxandroid-in-android-to-make-slow-network-call-and-update-th Thanks for your help. – Kamil Sep 20 '22 at 17:26

0 Answers0