2

当成功发出 http 请求时,我正在使用 Otto 将结果获取到片段。

在我的应用程序中,我有一个查看器。并且因为页面非常相似,所以我在 viewpager 中使用相同的片段和不同的数据来下载数据。

片段方法看起来像

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

    MMApp.getBus().register(this);
}


@Override
public void onPause() {
    super.onPause();
    MMApp.getBus().unregister(this);
}

  @Subscribe
public void onHttpResponseReceived(VolleySuccesObject results) {
}

数据混合在一起,例如第一页的结果也显示在第二页。有谁知道如何解决这个问题

4

2 回答 2

1

This is because ViewPager keeps multiple fragments started for performance reasons. If you want to know which fragment is really visible, you should override setUserVisibleHint() method and register/unregister fragments at the bus there. Be aware that this method defaults to true. This means Android won't call it with true value initially. Thus your logic inside setUserVisibleHint() must check registration status and call register()/unregister() only when needed. Same is valid for onStop() method. If unregister has been already called inside setUserVisibleHint() then you don't need to call it inside onPause(), otherwise Otto will throw an exception.

Open source TinyBus uses Otto-like API and has a special method called hasRegistered(Object) intended exactly for this situation, to check whether given object is registered to the bus or not.

于 2015-03-09T11:38:06.323 回答
0

我遇到了同样的问题。正如@sergej shafarenka 指出的那样,viewpagers 基本上会根据您的 viewpager 设置(默认为 1)预加载一个片段。

发生的事情是您为每个片段订阅了相同的对象(即,VolleySuccesObject对于您的情况)。现在,当您的 Fragment A 在前台时,Fragment B 也会被加载,它的生命周期也是如此,您在其中注册您的总线。

此时,Fragment A 和 B(假设您当前在 Fragment A)都在监听 VolleySuccesObject。

当然,该解决方案基于您的用例。我的场景是我发送一个Person基于id. 现在我的 Fragment A 和 B 将收到这些Person Aand Person B,但我的两个 Fragment 都会收到这个对象。我返回的Person对象没有给出 Person's id,所以这是一个大问题,因为我无法找出 Person 对象的用途。

解决方案: 我为我的 Person 对象 (PersonResponseWrapper) 使用了一个包装器,其中我的 API 服务负责返回包含PersonAND 和id. 因此,当我使用@Subscribe 时,我有以下代码:

private String mId; //id used for the API call

@Subscribe
public void onPersonReponseReceived(PersonResponseWrapper response) {
   if(mId.equalsIgnoreCase(response.getid()) { //Yup, this the Person object for me. Processing...
        process(response.getPerson());
   }
}

希望这有帮助。这困扰了我好几天!如果有人遇到类似要求,将回答此帖子。

于 2016-10-21T17:04:11.177 回答