2017-02-06 6 views
4

私は2回の非同期呼び出しを行い、元のリクエストに基づいて問題を解決しようとしていますが、私はタスクを実行しています。この問題を解決するために、各リクエストにTAGを追加しようとしていますが、成功したレスポンスでタグを取得してそのタグに基づいて行動を取ることができます。ここでは、元のリクエストを識別するためだけにTAGを使用しています。Retrofit元のリクエストオブジェクトにタグを追加する

問題

エンキュー・メソッドを呼び出す前に、私は、元の要求にタグを設定しています。しかし、コールバックが成功したときに応答が返ってくると、設定しなかった別のタグが表示されます。どういうわけか、リクエストオブジェクト自体がタグオブジェクトとして来ています。私は確信していない、どのように???

GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class); 
       final Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit"); 

       // Set the string tag to the original request object. 
       call.request().newBuilder().tag("hello").build(); 


       call.enqueue(new Callback<List<Contributor>>() { 
        @Override 
        public void onResponse(Call<List<Contributor>> call, Response<List<Contributor>> response) { 
         Log.d("tag", response.raw().request().tag().toString()); 
         // I'm getting Request{method=GET, url=https://api.github.com/repos/square/retrofit/contributors, tag=null} as the value of the tag. WHY???? 
         final TextView textView = (TextView) findViewById(R.id.textView); 
         textView.setText(response.body().toString()); 
        } 
        @Override 
        public void onFailure(Call<List<Contributor>> call, Throwable t) { 
         final TextView textView = (TextView) findViewById(R.id.textView); 
         textView.setText("Something went wrong: " + t.getMessage()); 
        } 
       }); 

below-コードを確認してください誰かがまさに私が間違ってここで何をやっていることを指摘することができます。どんな助けもありがとう。

答えて

3

このソリューションは明らかにハックですが、機能します。

は、あなたがこのようなあなたのレトロフィットサービスを作成しましょう:

public <S> S createService(Class<S> serviceClass) { 

    // Could be a simple "new" 
    Retrofit.Builder retrofitBuilder = getRetrofitBuilder(baseUrl); 

    // Could be a simple "new" 
    OkHttpClient.Builder httpClientBuilder = getOkHttpClientBuilder(); 

    // Build your OkHttp client 
    OkHttpClient httpClient = httpClientBuilder.build(); 

    Retrofit retrofit = retrofitBuilder.client(httpClient).build(); 

    return retrofit.create(serviceClass); 
} 

あなたはそれがすべてのタイムタグを追加しますので、お使いのレトロフィットインスタンスに新しいCallFactoryを追加する必要があります。タグは読み取り専用なので、1つの要素だけを含むObjectの配列を使用します。後で変更することができます。

Retrofit retrofit = retrofitBuilder.client(httpClient).callFactory(new Call.Factory() { 
     @Override 
     public Call newCall(Request request) { 

      request = request.newBuilder().tag(new Object[]{null}).build(); 

      Call call = httpClient.newCall(request); 

      // We set the element to the call, to (at least) keep some consistency 
      // If you want to only have Strings, create a String array and put the default value to null; 
      ((Object[])request.tag())[0] = call; 

      return call; 
     } 
    }).build(); 

今、あなたの呼び出しを作成した後、あなたがタグの内容を変更することができるようになります。

((Object[])call.request().tag())[0] = "hello"; 
+1

感謝。はい、それはハックです、それは働いています:-) –

関連する問題