在离开 activity 或片段 - android 时取消 Retrofit 请求或处理它们

Canceling Retrofit requests or handling them when leaving the activity or fragment - android

我使用 Retrofit library 来处理来自我的 WCF 网络服务的 JSON 响应。

RestService.getRestService().search("tools", new Callback<SearchResult>() {
    @Override
    public void success(SearchResult searchResult, Response response) {
        if( searchResult == null) return;
        textView.setText(searchResult.toString());
    } // end of success(

    @Override
    public void failure(RetrofitError error) {
            showToast(R.string.internet_sikintisi);

    }
});

我注意到如果我离开片段或 activity 我调用此函数的地方,我会收到错误消息。因为我在 textView 中设置了文本,其中 activity 或片段尚不存在。

我把代码修改成这样:

RestService.getRestService().search("tools", new Callback<SearchResult>() {
    @Override
    public void success(SearchResult searchResult, Response response) {

        if( searchResult == null) return;
        try{
            textView.setText(searchResult.toString());
        } catch(Exception e) {}

    } // end of success(

    @Override
    public void failure(RetrofitError error) {
        try{
                showToast(R.string.internet_sikintisi);
            } catch(Exception e) {}
    }
});

基本上,问题解决了,应用程序不会在用户每次立即进出时崩溃。这个问题可能还有更好的解决方案。

我检查过并且 Retrofit 没有 有取消请求功能!

您需要添加检查成功和失败的方法,就像您使用异步任务检查上下文是否仍然存在或创建您在 activity 的 onResume/onPause 上设置的 isActive 字段一样或片段。

可以取消 Retrofit 2 中的 Retrofit 请求(测试版现已推出。)

 call.cancel();// as simple as that