不继承RxAppCompatActivity的情况下使用RxLifeCycle

在Android中使用Rxjava时可能会在页面退出时出现内存泄漏的情况,RxLifeCycle就是为此而生,但是作者在sample中写得很简单,只用了继承RxAppCompatActivity的案例讲解它的用法。但是用户在使用过程中,可能会因为继承了别的Activity,不好再继承RxAppCompatActivity,这种情况怎么办呢?

其实作者已经为我们提供了解决方案,只是没有在sample中讲解罢了,下面,我通过两个小例子讲一下在不继承RxAppCompatActivity或RxFragment时如何使用RxLifeCycle:

1. 添加依赖:

compile 'com.trello.rxlifecycle2:rxlifecycle-android-lifecycle:2.2.1'


2. 在AppCompatActivity中使用:

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LifecycleProvider lifecycleProvider = AndroidLifecycle.createLifecycleProvider(this);
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose(new Action() {
@Override
public void run() throws Exception {
Log.e(TAG, "unSubscribe subscription");
}
})
.compose(lifecycleProvider.bindUntilEvent(Lifecycle.Event.ON_DESTROY))
.subscribe(new Consumer() {
@Override
public void accept(Long num) throws Exception {
Log.e(TAG, "running until onDestroy(): " + num);
}
});
}
}


3. 在Fragment中使用:

public class TestFragment extends Fragment {

private static final String TAG = "TestFragment";

public TestFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LifecycleProvider lifecycleProvider = AndroidLifecycle.createLifecycleProvider(this);
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose(new Action() {
@Override
public void run() throws Exception {
Log.e(TAG, "UnSubscribing subscription");
}
})
.compose(lifecycleProvider.bindUntilEvent(Lifecycle.Event.ON_PAUSE))
.subscribe(new Consumer() {
@Override
public void accept(Long num) throws Exception {
Log.e(TAG, "Running until onPause(): " + num);
}
});
}
}

你可能感兴趣的:(android应用开发)