Retrofit callback on main thread

2020-05-26 13:41发布

With a call like :

@GET("/user/{id}/data")
void getUserData(@Path("id") int id, Callback<Data> cb);

Callback is supposed to be executed on the main thread (if not using RxJava). My questions are :

  1. Where does the parsing happen (let's assume I am using an XML converter for process response). Is this main thread, or a different one ? Does it depend on converter implementation ?
  2. If I have to include some (heavy) validation rule/business rules, do I need to spawn a new thread inside callable ? Or is it fine to have it done in the Callback methods ?

I am looking for ways to get data in my activity from a web-service avoiding thread-management on my own (or using other approaches like IntentService, etc.), but am afraid of using RxJava either (because of experimental support). Is there another suggested approach to deal with this problem ?

1条回答
老娘就宠你
2楼-- · 2020-05-26 14:01

Where does the parsing happen (let's assume I am using an XML converter for process response). Is this main thread, or a different one ? Does it depend on converter implementation ?

Always a background thread no matter the converter you use.

If I have to include some (heavy) validation rule/business rules, do I need to spawn a new thread inside callable ? Or is it fine to have it done in the Callback methods ?

This is fairly subjective and there's a lot of ways to tackle it. The Callback will be executed on the main thread by default.

You can change the thread on which callbacks will be invoked by supplying a custom Executor to the RestAdapter.Builder. This will affect all services constructed by that RestAdapter, however, which may not be what you want.

There's nothing wrong with spawning another thread (or enqueueing on an executor) from the Callback if the work you want to be done can be done in parallel with updating the UI (for example, light-weight caching).

If the expensive work must be done before notifying the UI then you are better off switching the method to be synchronous (no callback) and doing the threading yourself. This way you can do expensive operations before and after the HTTP call (file i/o, caching, transforming, validating, etc.).

We currently use RxJava (of which Retrofit has experimental support) for what you are asking:

interface Foo {
  @GET("/")
  Observable<Foo> getFoo(String bar);
}

foo.getFoo()
  .mapMany(new ExpensiveOperationFunction())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Observer<TransformedFoo>() { .. });
查看更多
登录 后发表回答