Retrofit callback on main thread

前端 未结 1 595
天命终不由人
天命终不由人 2021-02-05 13:37

With a call like :

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

Callback is supposed to be execut

1条回答
  •  孤独总比滥情好
    2021-02-05 14:03

    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 getFoo(String bar);
    }
    
    foo.getFoo()
      .mapMany(new ExpensiveOperationFunction())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Observer() { .. });
    

    0 讨论(0)
提交回复
热议问题