我有一个Observable改变了edittext的值,edittext中的值将被传递给观察者并将其设置为textview,如图所示 在下面的代码中。
我要做的是取消订阅观察。 请帮我取消订阅观察,我的尝试是在代码belwo
//How to subscribe
//widgetObservable.unsubscribeOn();
//widgetObservable.unsafeSubscribe();
//widgetObservable.doOnUnsubscribe();
码:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView mTextView = null;
private EditText mEditText = null;
private View mButton = null;
private rx.Observable<String> widgetObservable = null;
Subscriber widgetSubscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
Log.i(TAG, "onCompleted");
}
@Override
public void onError(Throwable e) {
Log.i(TAG, "onError: " + e.getMessage().toString());
}
@Override
public void onNext(String str) {
Log.i(TAG, "onNext: " + str);
mTextView.setText(str);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textview);
mEditText = (EditText) findViewById(R.id.editText);
mButton = findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
widgetObservable.subscribe(widgetSubscriber);
//How to subscribe
//widgetObservable.unsubscribeOn();
//widgetObservable.unsafeSubscribe();
//widgetObservable.doOnUnsubscribe();
}
});
widgetObservable = rx.Observable.create(new rx.Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext(mEditText.getText().toString());
subscriber.onCompleted();
}
});
}
}
答案 0 :(得分:1)
添加此内容!
@Override
protected void onDestroy() {
super.onDestroy();
widgetObservable.unsubscribe();
}
答案 1 :(得分:0)
private Subscription subscription;
subscription = widgetObservable.subscribe(widgetSubscriber);
if (subscription != null) {
subscription.unsubscribe()
}
unsubscibe应该在Activity的onDestroy方法
中完成