gpt4 book ai didi

android - 仅当 Fragment 在 ViewPager 中可见时才触发 RxJava 事件更改

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:11:16 29 4
gpt4 key购买 nike

我在 Activity 中有一个 EditText,用户可以在其中键入和搜索内容。在搜索栏下方,我有 2 个 tabs 附加到 ViewPager。我在标签的 2 个 Fragments 中为 EditText 添加了一个 RxJava 事件更改监听器。相关代码如下:

    private Subscription subscription;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_people_search, container, false);
ButterKnife.bind(this, view);
LogUtil.i(TAG, "onCreateView called");

if (getActivity() != null) {
inputSearch = (EditText) getActivity().findViewById(R.id.editText11);
}

return view;
}

@Override
public void onResumeFragment() {
LogUtil.i(TAG, "onResumeFragment called");
if (subscription == null) {
doSearch();
}
}

private void doSearch() {
LogUtil.i(TAG, "doSearch called");
subscription = RxTextView.textChangeEvents(inputSearch)
.debounce(400, TimeUnit.MILLISECONDS)
.map(new Func1<TextViewTextChangeEvent, String>() {
@Override
public String call(TextViewTextChangeEvent textViewTextChangeEvent) {
return textViewTextChangeEvent.text().toString().trim();
}
})
.switchMap(new Func1<String, Observable<SearchUserData>>() {
@Override
public Observable<SearchUserData> call(String s) {
term = s;
if (previousTerm.equalsIgnoreCase(term) && TextUtils.isEmpty(term)) {
//do not reset pagination variables
} else if (!previousTerm.equalsIgnoreCase(term) && TextUtils.isEmpty(term)) {
min = 0;
max = 14;
} else if (previousTerm.equalsIgnoreCase(term) && !TextUtils.isEmpty(term)) {
//do not reset pagination variables
} else {
min = 0;
max = 14;
}
loadMoreOrNot = true;
previousTerm = term;
DiscoverAPI discoverAPI = restAdapter.create(DiscoverAPI.class);
return discoverAPI.getRxPeopleSearchResult(min, max, s, "user");
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getRxSearchObserver());
}

我想要的是,当我搜索某些内容时,查询应该只针对当前选择的选项卡进入后端,而不是针对这两个选项卡。我该怎么做?

最佳答案

我认为有两种选择。

使用过滤器:

    subscription = RxTextView.textChangeEvents(inputSearch)
.debounce(400, TimeUnit.MILLISECONDS)
.filter(textViewTextChangeEvent -> getUserVisibleHint())
.map(..)
...

或者在调用 setUserVisibleHint 时订阅/取消订阅(正如@Amir 评论的那样):

    @Override
public void onResumeFragment() {
//don't subscribe here
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);

if (subscription != null) {
subscription.unsubscribe();
subscription = null;
}
if (isVisibleToUser) {
doSearch();
}
}

@Override
public void onDestroyView() {
super.onDestroyView();

if (subscription != null) {
subscription.unsubscribe();
subscription = null;
}
}

关于android - 仅当 Fragment 在 ViewPager 中可见时才触发 RxJava 事件更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39292308/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com