-2

everyone!

I'm building an app for the company where I work and we have to run an interaction with an API in the background, but while this interaction is running, the interaction sends us some messages that must enable/disable some views in activity/fragment.

We are running this interaction using the async task, but the problem is: I can't update a view attribute when the message comes from a background thread. I had to use a custom Progress class to handle those messages and then change the view attributes.

In our app, we are using MVVP pattern, and my async task is called from a ViewModel, which is responsible for execute the bizness logic.

But what I really want to know is: Is there another way to perform an async task without using an AsyncTask subclass? Maybe some of you guys can halp me out recommending a way that use callbacks to notify messages and when the function ends.

I know that Retrofit makes an asynchronous task using the enqueue method, but I didn't understand how can I implement that way by myself.

Ps.: The AsyncTask subclass is working fine, but I didn't get along with that implementation.

  • You have some options like `Executers` or `Coroutines`(Kotlin) .. – ADM Dec 17 '18 at 12:12
  • You sure you don't mean the mvvm (model-view-viewmodel) pattern since you use viewmodels? – findusl Dec 17 '18 at 15:37
  • I don't like it when someone downvotes a question but doesn't explain why... Wasn't me. Anyway, your question isn't very good as you assume "I can't update a view attribute when the message comes from a background thread." which is wrong as Alexei pointed out in his answer. See https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – findusl Dec 17 '18 at 15:39

2 Answers2

1

Why can't you update a view attribute when the message comes from a background thread? it can be done in many ways.

Anyway, there is no other way out, since I/O operations cannot be performed on the GUI thread, only on some background thread.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
0

You can take a look at libraries like retrofit for performing API calls. Also, if you are using kotlin you can take a look at coroutines for a more generic asyncronous work.

Eric Martori
  • 2,885
  • 19
  • 26
  • I was planning to use coroutines, but I didn't understand how it works. Yesterday I started to learn more about coroutine and maybe I can use MutableLiveData#post() method. I think it can work using AsyncTask subclasses. – Jonathan Giorgi Silveira Dec 18 '18 at 10:52