Best way to decouple REST call from `Activity`

对着背影说爱祢 提交于 2020-01-15 07:34:05

问题


I am using Retrofit and want REST calls to survive when the user navigates between my activities (as opposed to just retaining them accross configuration changes). Couple of options:

  1. Retrofit syncronous call within an AsyncTask and put that in a retained "task fragment"
  2. Retrofit syncronous call within an IntentService and broadcast
  3. Google suggests a per-app singleton, at least with Volley...

What is the best approach? And I can see RxJava as a Retrofit mode but even there one is just adviced to "unsubscribe from the returned Observable in onDestroy at the latest" - so not a real solution, despite all hype about the new built-in Rx support.


回答1:


I don't think a retained fragment will achieve what you want here. It can help with handling configuration changes, but not between activities.

You probably should break your problem into 2 problems, one is where to start the network call, and other is receiving the response.

For the first problem, you can start the network call in the Activity/Fragment normally. If you're going to do this a lot though, you'll probably want to manage the calls in a Service and use some sort of queue.

To receive the response, you should just make sure your listener (Callback or Subscriber) isn't tied to your Activity/Fragment instance (using static for nested classes, or top-level classes). You can then forward the result to the Activity using a broadcast or EventBus/Otto.

This can be either handled in you Callback/Subscriber, or inside Service context. (Though if you want to use Broadcast inside Activity, you should reference Context.getApplicationContext() instead of the current Activity context, in case your Activity is destroyed)

Doing this your network calls should resume normally without errors, even when the Activity that requested them is stopped.

The final step would be to cache the response, because if the Activity is stopped, then the response will go no where. Even though the network call was completed, it was wasted. You should cache these responses in some way so your Activity/Fragment can retrieve them upon recreation.

Personally I would go for Service with EventBus combination.



来源:https://stackoverflow.com/questions/26239650/best-way-to-decouple-rest-call-from-activity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!