在使用Observable.unsubscribeOn()时Observable.unsubscribeOn()调用/ when时是一个Observable取消订阅

时间:2017-03-08 08:16:54

标签: android rx-android rx-java2

我正在this链接中学习该教程,并编写了以下代码。

public class CheeseActivity extends BaseSearchActivity {
Observable<String> textInput = Observable.create(
        e -> {
            try {
                //emit what the user types in the text field
                String query = mQueryEditText.getText().toString().trim();
                Log.e("myapp", query + " 0");
                e.onNext(query);

                e.onComplete();
            } catch (Exception ex) {
                e.onError(ex);
            }
        }
);

@Override
protected void onStart() {
    super.onStart();
    Button searchbtn = mSearchButton;

    searchbtn.setOnClickListener(view -> {
        textInput
                //show the progressbar in ui thread
                .observeOn(AndroidSchedulers.mainThread()).doOnNext(query -> {
            Log.e("myapp", query + " 1");
            showProgressBar();
        })
                //perform the search in io thread
                .observeOn(Schedulers.io()).map(query -> mCheeseSearchEngine.search(query))
                //show search result in ui thread
                .observeOn(AndroidSchedulers.mainThread()).subscribe(results -> {
            Log.e("myapp", "search finished");
            hideProgressBar();
            showResult(results);
        });
        Log.e("myapp", "unsubbed");
    });
    textInput.unsubscribeOn(AndroidSchedulers.mainThread());

}
}

这里是logcat(ch是从edittext字段中取出的字符串)

E / myapp:ch 0

E / myapp:unsubbed

E / myapp:ch 1

E / myapp:搜索完

显然,点击按钮后会立即打印“未取消”。  但我想在 textInput Observable取消订阅后立即打印“unsubbed”。我该怎么做?

1 个答案:

答案 0 :(得分:0)

刚学会了 .doFinally(() - &gt; Log.e(&#34; myapp&#34;,&#34; unsubbed&#34;))就在.subscribe(...)

之前