使用Retrofit和RxJava的生命周期管理

来源:互联网 发布:js开发日历时间控件 编辑:程序博客网 时间:2024/05/16 14:48
On Android it is tricky for asynchronous actions to access framework objects in their callbacks. That’s because Android may decide to destroy an Activity, for instance, while a background thread is still running. The thread will attempt to access views on the now dead Activity, which results in a crash. (This will also create a memory leak, since your background thread holds on to the Activity even though it’s not visible anymore.)

This is still a concern when using RxJava on Android, but you can deal with the problem in a more elegant way by using Subscriptions and a number of Observable operators. In general, when you run an Observable inside an Activity that subscribes to the result (either directly or through an inner class), you must unsubscribe from the sequence in onDestroy, as shown in the following example:

// MyActivityprivate Subscription subscription;protected void onCreate(Bundle savedInstanceState) {    this.subscription = observable.subscribe(this);}...protected void onDestroy() {    this.subscription.unsubscribe();    super.onDestroy();}

This ensures that all references to the subscriber (the Activity) will be released as soon as possible, and no more notifications will arrive at the subscriber through onNext.

One problem with this is that if the Activity is destroyed because of a change in screen orientation, the Observable will fire again in onCreate. You can prevent this by using the cache or replay Observable operators, while making sure the Observable somehow survives theActivity life-cycle (for instance, by storing it in a global cache, in a Fragment, etc.) You can use either operator to ensure that when the subscriber subscribes to an Observable that’s already “running,” items emitted by the Observable during the span when it was detached from theActivity will be “played back,” and any in-flight notifications from the Observable will be delivered as usual.

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 和对象想分手了怎么办 对象想跟你啪啪怎么办 相亲对象好像不太想理我怎么办 想跟对象分手了怎么办 异地恋分手后该怎么办 面膜敷了一晚上怎么办 梦见被刺猬咬了怎么办 梦见死人叫我名字答应怎么办 香瓜苗叶子长斑怎么办 奶油打出来很稀怎么办 寄的水果压坏了怎么办 吃了一个烂水果怎么办 孕期吃了烂水果怎么办 邮快递水果坏了怎么办 快递寄水果坏了怎么办 闲鱼买家拒收水果怎么办 洗澡桶里有很多老鼠屎怎么办? 塑料和金属断了怎么办 孕妇吃了沙拉酱怎么办 孕妇淀粉吃多了怎么办 怀孕初期吃了杏怎么办 如果睡觉吃梨了怎么办 怀孕6个月有点贫血怎么办 怀孕八个多月有点贫血怎么办 生完小孩身体虚怎么办 孩子咳嗽厉害怎么办吃什么药 新生儿三天不拉大便怎么办 胃吃的变大了怎么办 小孩长高长的慢怎么办 小孩长高长得慢怎么办 小孩吃东西不吸收营养怎么办 婴儿长得太快怎么办 2个月婴儿长太快怎么办 孩子脚长得太快怎么办 4个月宝宝缺钙怎么办 2个月宝宝不长肉怎么办 小孩子长得不高怎么办 宝宝误吃蜂蜜了怎么办 有人拿着吃完的东西退货怎么办 婴儿个子长的慢怎么办 儿童长得太快怎么办