我稍微更改了RxAndroid 示例以在后台执行点击任务,但它不起作用:-(
这是我的代码:
/**
* Simple example of creating a Subscription that is bound to the lifecycle
* (and thus automatically unsubscribed when the Activity is destroyed).
*/
public class LifecycleObservableActivity extends RxActivity {
private static final String TAG = LifecycleObservableActivity.class.getSimpleName();
private Button button;
private Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
button = new Button(this);
button.setText("Click Me!");
setContentView(button);
}
@Override
protected void onStart() {
super.onStart();
Observable<OnClickEvent> clicks = ViewObservable.clicks(button)
// .subscribeOn(Schedulers.computation()); IllegalStateException: Observers must subscribe from the main UI thread, but was Thread[RxComputationThreadPool-3,5,main]
.observeOn(Schedulers.computation());
subscription =
LifecycleObservable.bindActivityLifecycle(lifecycle(), clicks)
.map(x -> {
Log.i(TAG, "Func1 - main thread: " + isCurrentlyOnMainThread() + " (" + Thread.currentThread() + ")");
return "hallo welt";
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(string -> {
Log.i(TAG, "Action1 - main thread: " + isCurrentlyOnMainThread() + " (" + Thread.currentThread() + ")");
Toast.makeText(LifecycleObservableActivity.this,
string,
Toast.LENGTH_SHORT)
.show();
});
}
@Override
protected void onPause() {
super.onPause();
// Should output "false"
Log.i(TAG, "onPause(), isUnsubscribed=" + subscription.isUnsubscribed());
}
@Override
protected void onStop() {
super.onStop();
// Should output "true"
Log.i(TAG, "onStop(), isUnsubscribed=" + subscription.isUnsubscribed());
}
private boolean isCurrentlyOnMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
}
当我运行它时,我得到这个日志:
Func1 - main thread: false (Thread[RxComputationThreadPool-3,5,main])
Action1 - main thread: true (Thread[main,5,main])
onPause(), isUnsubscribed=false
onStop(), isUnsubscribed=false
Func1 在目前正确的后台运行。但是订阅并没有取消订阅。只有当 Func1 也在 UI 线程中运行时,它才会取消订阅。
我必须更改 Func1 在后台运行并且订阅将被取消订阅?