codeestX / GeekNews

:books:A pure reading App based on Material Design + MVP + RxJava2 + Retrofit + Dagger2 + Realm + Glide
3.49k stars 826 forks source link

关于内存泄露的问题 #98

Closed caopeng000 closed 7 years ago

caopeng000 commented 7 years ago

hi,哥们还是我,哈哈。想问你个关于内存泄露的问题,如果在网络请求还没有返回的时候,界面退出,有可能会造成空指针异常。实例:ThemeChildPresenter `@Override public void getThemeChildData(final int id) { new Handler().postDelayed(new Runnable() { @Override public void run() { addSubscribe(mDataManager.fetchThemeChildListInfo(id) .compose(RxUtil.rxSchedulerHelper()) .map(new Function<ThemeChildListBean, ThemeChildListBean>() { @Override public ThemeChildListBean apply(ThemeChildListBean themeChildListBean) { List list = themeChildListBean.getStories(); for (ThemeChildListBean.StoriesBean item : list) { item.setReadState(mDataManager.queryNewsId(item.getId())); } return themeChildListBean; } }) .subscribeWith(new CommonSubscriber(mView) { @Override public void onNext(ThemeChildListBean themeChildListBean) { Log.i("TAG", "----主题界面的请求回调onNext"); mView.showContent(themeChildListBean); } }) ); } }, 1000);

}`

我给网络请求延迟了1秒,然后我进去界面马上退出,然后网络请求回调成功后,调用showContent,然后就崩溃了。对于这种情况需要做特殊处理吗,比如判断mView!=null

codeestX commented 7 years ago

@caopeng000 Hi,这种情况应该是Handler造成的泄漏导致这次addSubscribeRxPresenterunSubscribe();之后执行了,所以订阅没被清掉。可以用mView!=null做特殊处理,不过最好避免泄漏从根源上解决问题..

caopeng000 commented 7 years ago

恩恩,老铁没毛病。哈哈