我创建了viewpager
,fragment
有RecyclerView
& viewholder
。
@Override
public void bindModel(GankInfo item) {
super.bindModel(item);
picViewPager.setOnTouchListener(((v, event) -> {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:{
stopPlay();
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:{
startPlay();
break;
}
}
return false;
}));
}
@Override
public void onAttach() {
super.onAttach();
startPlay();
}
@Override
public void onDetach() {
super.onDetach();
stopPlay();
}
private void stopPlay(){
subscription.unsubscribe();
}
private void startPlay(){
subscription =
Observable.interval(3, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> {
int currentPosition = picViewPager.getCurrentItem();
currentPosition++;
picViewPager.setCurrentItem(currentPosition==picViewPager.getAdapter().getCount()?0:currentPosition);
});
}
我使用Leakcanary
来查找片段的内存泄漏。当我滑动viewpager时,片段会泄漏内存。我用adapter.onViewDetachedFromWindow
称这个停止并且泄漏将总是多次通知。我尝试谷歌一些方法来解决我的问题,但那些无法正常工作。这里:
答案 0 :(得分:4)
为什么Observable.interval()无法取消订阅
如果您不小心拨打startPlay
两次,则会覆盖以前的订阅,因此您正在泄漏它。要克服它,您只能在订阅取消订阅时订阅。 E.g。
Subscription subscription = Subscriptions.unsubscribed();
private void startPlay(){
if (subscription.isUnsubscribed()) {
subscription =
Observable.interval(3, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> {
int currentPosition = picViewPager.getCurrentItem();
currentPosition++;
picViewPager.setCurrentItem(currentPosition==picViewPager.getAdapter().getCount()?0:currentPosition);
});
}
}