com.apollographql.apollo.api.Response Java Examples

The following examples show how to use com.apollographql.apollo.api.Response. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitHuntEntryDetailActivity.java    From HelloApolloAndroid with MIT License 7 votes vote down vote up
private void fetchRepositoryDetails() {
    ApolloCall<EntryDetailQuery.Data> entryDetailQuery = application.apolloClient()
            .query(new EntryDetailQuery(repoFullName))
            .cacheControl(CacheControl.CACHE_FIRST);

    //Example call using Rx2Support
    disposables.add(Rx2Apollo.from(entryDetailQuery)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableSingleObserver<Response<EntryDetailQuery.Data>>() {
                @Override
                public void onSuccess(Response<EntryDetailQuery.Data> dataResponse) {
                    setEntryData(dataResponse.data());
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }));
}
 
Example #2
Source File: ApolloPrefetchTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void prefetchNoCacheStore() throws Exception {
  ApolloClient apolloClient = ApolloClient.builder()
      .serverUrl(server.url("/"))
      .okHttpClient(okHttpClient)
      .dispatcher(Utils.INSTANCE.immediateExecutor())
      .build();

  server.enqueue(Utils.INSTANCE.mockResponse("HttpCacheTestAllPlanets.json"));
  prefetch(apolloClient.prefetch(new AllPlanetsQuery()));

  Utils.INSTANCE.enqueueAndAssertResponse(
      server,
      "HttpCacheTestAllPlanets.json",
      apolloClient.query(new AllPlanetsQuery()),
      new Predicate<Response<AllPlanetsQuery.Data>>() {
        @Override public boolean test(Response<AllPlanetsQuery.Data> response) throws Exception {
          return !response.hasErrors();
        }
      }
  );
}
 
Example #3
Source File: IntegrationTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void errorResponse_with_data() throws Exception {
  server.enqueue(mockResponse("ResponseErrorWithData.json"));
  assertResponse(
      apolloClient.query(new EpisodeHeroNameQuery(Input.fromNullable(JEDI))),
      new Predicate<Response<EpisodeHeroNameQuery.Data>>() {
        @Override public boolean test(Response<EpisodeHeroNameQuery.Data> response) throws Exception {
          assertThat(response.data()).isNotNull();
          assertThat(response.data().hero().name()).isEqualTo("R2-D2");
          assertThat(response.errors()).containsExactly(new Error(
              "Cannot query field \"names\" on type \"Species\".",
              Collections.singletonList(new Error.Location(3, 5)), Collections.<String, Object>emptyMap()));
          return true;
        }
      }
  );
}
 
Example #4
Source File: ApolloInterceptorTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void applicationInterceptorCanMakeMultipleRequestsToServer() throws Exception {
  server.enqueue(mockResponse(FILE_EPISODE_HERO_NAME_CHANGE));
  EpisodeHeroNameQuery query = createHeroNameQuery();
  ApolloInterceptor interceptor = createChainInterceptor();

  client = createApolloClient(interceptor);

  Utils.INSTANCE.enqueueAndAssertResponse(
      server,
      FILE_EPISODE_HERO_NAME_WITH_ID,
      client.query(query),
      new Predicate<Response<EpisodeHeroNameQuery.Data>>() {
        @Override public boolean test(Response<EpisodeHeroNameQuery.Data> response) throws Exception {
          assertThat(response.data().hero().name()).isEqualTo("Artoo");
          return true;
        }
      }
  );
}
 
Example #5
Source File: Rx3Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloQueryWatcher} to an asynchronous Observable.
 *
 * @param watcher the ApolloQueryWatcher to convert.
 * @param <T>     the value type
 * @return the converted Observable
 * @throws NullPointerException if watcher == null
 */
@NotNull
@CheckReturnValue
public static <T> Observable<Response<T>> from(@NotNull final ApolloQueryWatcher<T> watcher) {
  checkNotNull(watcher, "watcher == null");
  return Observable.create(new ObservableOnSubscribe<Response<T>>() {
    @Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
      cancelOnObservableDisposed(emitter, watcher);

      watcher.enqueueAndWatch(new ApolloCall.Callback<T>() {
        @Override public void onResponse(@NotNull Response<T> response) {
          if (!emitter.isDisposed()) {
            emitter.onNext(response);
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }
      });
    }
  });
}
 
Example #6
Source File: IntegrationTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void parseErrorOperationRawResponse() throws Exception {
  final EpisodeHeroNameQuery query = new EpisodeHeroNameQuery(Input.fromNullable(EMPIRE));
  final Response<EpisodeHeroNameQuery.Data> response = query.parse(
      new Buffer().readFrom(getClass().getResourceAsStream("/ResponseErrorWithData.json")),
      new ScalarTypeAdapters(Collections.<ScalarType, CustomTypeAdapter<?>>emptyMap())
  );

  assertThat(response.data()).isNotNull();
  assertThat(response.data().hero()).isNotNull();
  assertThat(response.data().hero().name()).isEqualTo("R2-D2");
  assertThat(response.errors()).containsExactly(
      new Error(
          "Cannot query field \"names\" on type \"Species\".",
          Collections.singletonList(new Error.Location(3, 5)),
          Collections.<String, Object>emptyMap()
      )
  );
}
 
Example #7
Source File: NormalizedCacheTestCase.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void heroAppearsInResponse() throws Exception {
  Utils.INSTANCE.cacheAndAssertCachedResponse(
      server,
      "HeroAppearsInResponse.json",
      apolloClient.query(new HeroAppearsInQuery()),
      new Predicate<Response<HeroAppearsInQuery.Data>>() {
        @Override
        public boolean test(Response<HeroAppearsInQuery.Data> response) throws Exception {
          assertThat(response.hasErrors()).isFalse();
          assertThat(response.data().hero().appearsIn()).hasSize(3);
          assertThat(response.data().hero().appearsIn().get(0).name()).isEqualTo("NEWHOPE");
          assertThat(response.data().hero().appearsIn().get(1).name()).isEqualTo("EMPIRE");
          assertThat(response.data().hero().appearsIn().get(2).name()).isEqualTo("JEDI");
          return true;
        }
      }
  );
}
 
Example #8
Source File: ApolloInterceptorTest.java    From apollo-android with MIT License 6 votes vote down vote up
@NotNull private InterceptorResponse prepareInterceptorResponse(EpisodeHeroNameQuery query) {
  Request request = new Request.Builder()
      .url(server.url("/"))
      .build();

  okhttp3.Response okHttpResponse = new okhttp3.Response.Builder()
      .request(request)
      .protocol(Protocol.HTTP_2)
      .code(200)
      .message("Intercepted")
      .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "fakeResponse"))
      .build();

  Response<EpisodeHeroNameQuery.Data> apolloResponse = Response.<EpisodeHeroNameQuery.Data>builder(query).build();

  return new InterceptorResponse(okHttpResponse,
      apolloResponse, Collections.<Record>emptyList());
}
 
Example #9
Source File: NormalizedCacheTestCase.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void heroAndFriendsNameWithIdsForParentOnly() throws Exception {
  Utils.INSTANCE.cacheAndAssertCachedResponse(
      server,
      "HeroAndFriendsNameWithIdsParentOnlyResponse.json",
      apolloClient.query(new HeroAndFriendsNamesWithIDForParentOnlyQuery(Input.fromNullable(Episode.NEWHOPE))),
      new Predicate<Response<HeroAndFriendsNamesWithIDForParentOnlyQuery.Data>>() {
        @Override
        public boolean test(Response<HeroAndFriendsNamesWithIDForParentOnlyQuery.Data> response) throws Exception {
          assertThat(response.hasErrors()).isFalse();
          assertThat(response.data().hero().id()).isEqualTo("2001");
          assertThat(response.data().hero().name()).isEqualTo("R2-D2");
          assertThat(response.data().hero().friends()).hasSize(3);
          assertThat(response.data().hero().friends().get(0).name()).isEqualTo("Luke Skywalker");
          assertThat(response.data().hero().friends().get(1).name()).isEqualTo("Han Solo");
          assertThat(response.data().hero().friends().get(2).name()).isEqualTo("Leia Organa");
          return true;
        }
      }
  );
}
 
Example #10
Source File: NormalizedCacheTestCase.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void heroAndFriendsNamesWithIDs() throws Exception {
  Utils.INSTANCE.cacheAndAssertCachedResponse(
      server,
      "HeroAndFriendsNameWithIdsResponse.json",
      apolloClient.query(new HeroAndFriendsNamesWithIDsQuery(Input.fromNullable(Episode.NEWHOPE))),
      new Predicate<Response<HeroAndFriendsNamesWithIDsQuery.Data>>() {
        @Override public boolean test(Response<HeroAndFriendsNamesWithIDsQuery.Data> response) throws Exception {
          assertThat(response.hasErrors()).isFalse();
          assertThat(response.data().hero().id()).isEqualTo("2001");
          assertThat(response.data().hero().name()).isEqualTo("R2-D2");
          assertThat(response.data().hero().friends()).hasSize(3);
          assertThat(response.data().hero().friends().get(0).id()).isEqualTo("1000");
          assertThat(response.data().hero().friends().get(0).name()).isEqualTo("Luke Skywalker");
          assertThat(response.data().hero().friends().get(1).id()).isEqualTo("1002");
          assertThat(response.data().hero().friends().get(1).name()).isEqualTo("Han Solo");
          assertThat(response.data().hero().friends().get(2).id()).isEqualTo("1003");
          assertThat(response.data().hero().friends().get(2).name()).isEqualTo("Leia Organa");
          return true;
        }
      }
  );
}
 
Example #11
Source File: ApolloWatcherTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void testQueryWatcherNotUpdated_SameQuery_SameResults() throws Exception {
  final List<String> heroNameList = new ArrayList<>();
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));

  ApolloQueryWatcher<EpisodeHeroNameQuery.Data> watcher = apolloClient.query(query).watcher();
  watcher.enqueueAndWatch(
      new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
        @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
          heroNameList.add(response.data().hero().name());
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Assert.fail(e.getMessage());
        }
      });

  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));
  apolloClient.query(query).responseFetcher(NETWORK_ONLY).enqueue(null);

  watcher.cancel();
  assertThat(heroNameList.get(0)).isEqualTo("R2-D2");
  assertThat(heroNameList.size()).isEqualTo(1);
}
 
Example #12
Source File: HttpCacheTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void networkOnly_DoNotStore() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery())
      .httpCachePolicy(HttpCachePolicy.NETWORK_ONLY)
      .cacheHeaders(CacheHeaders.builder().addHeader(ApolloCacheHeaders.DO_NOT_STORE, "true").build()))
      .test()
      .assertValue(new Predicate<Response<AllPlanetsQuery.Data>>() {
        @Override public boolean test(Response<AllPlanetsQuery.Data> response) throws Exception {
          return !response.hasErrors();
        }
      });
  assertThat(server.getRequestCount()).isEqualTo(1);
  assertThat(lastHttResponse.networkResponse()).isNotNull();
  assertThat(lastHttResponse.cacheResponse()).isNull();

  checkNoCachedResponse();
}
 
Example #13
Source File: ApolloWatcherTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testQueryWatcherNotUpdated_DifferentQueries() throws Exception {
  final List<String> heroNameList = new ArrayList<>();
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();

  ApolloQueryWatcher<EpisodeHeroNameQuery.Data> watcher = apolloClient.query(query).watcher();
  watcher.enqueueAndWatch(
      new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
        @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
          heroNameList.add(response.data().hero().name());
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Assert.fail(e.getMessage());
        }
      });

  HeroAndFriendsNamesWithIDsQuery friendsQuery = HeroAndFriendsNamesWithIDsQuery.builder().episode(Episode.NEWHOPE).build();

  server.enqueue(Utils.INSTANCE.mockResponse("HeroAndFriendsNameWithIdsResponse.json"));
  apolloClient.query(friendsQuery).responseFetcher(NETWORK_ONLY).enqueue(null);

  watcher.cancel();
  assertThat(heroNameList.get(0)).isEqualTo("R2-D2");
  assertThat(heroNameList.size()).isEqualTo(1);
}
 
Example #14
Source File: ApolloIdlingResourceTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void checkIsIdleNow_whenCallIsQueued() throws InterruptedException {
  server.enqueue(mockResponse());

  final CountDownLatch latch = new CountDownLatch(1);

  ExecutorService executorService = Executors.newFixedThreadPool(1);

  apolloClient = ApolloClient.builder()
      .okHttpClient(okHttpClient)
      .dispatcher(executorService)
      .serverUrl(server.url("/"))
      .build();

  idlingResource = ApolloIdlingResource.create(IDLING_RESOURCE_NAME, apolloClient);
  assertThat(idlingResource.isIdleNow()).isTrue();

  apolloClient.query(EMPTY_QUERY).enqueue(new ApolloCall.Callback<Object>() {
    @Override public void onResponse(@NotNull Response<Object> response) {
      latch.countDown();
    }

    @Override public void onFailure(@NotNull ApolloException e) {
      throw new AssertionError("This callback can't be called.");
    }
  });
  assertThat(idlingResource.isIdleNow()).isFalse();

  latch.await(TIME_OUT_SECONDS, TimeUnit.SECONDS);

  executorService.shutdown();
  executorService.awaitTermination(TIME_OUT_SECONDS, TimeUnit.SECONDS);
  Thread.sleep(100);
  assertThat(idlingResource.isIdleNow()).isTrue();
}
 
Example #15
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void cacheDefault() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test()
      .assertValue(new Predicate<Response<AllPlanetsQuery.Data>>() {
        @Override public boolean test(Response<AllPlanetsQuery.Data> response) throws Exception {
          return !response.hasErrors();
        }
      });
  checkCachedResponse("/HttpCacheTestAllPlanets.json");
}
 
Example #16
Source File: ApolloCall.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * <p>Gets called when an http request error takes place. This is the case when the returned http status code
 * doesn't lie in the range 200 (inclusive) and 300 (exclusive).</p>
 *
 * <b>NOTE:</b> by overriding this callback you must call {@link okhttp3.Response#close()} on {@link
 * ApolloHttpException#rawResponse} to close the network connection.
 */
public void onHttpError(@NotNull ApolloHttpException e) {
  onFailure(e);
  okhttp3.Response response = e.rawResponse();
  if (response != null) {
    response.close();
  }
}
 
Example #17
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
private void checkCachedResponse(String fileName) throws IOException {
  String cacheKey = lastHttRequest.headers(HttpCache.CACHE_KEY_HEADER).get(0);
  okhttp3.Response response = apolloClient.cachedHttpResponse(cacheKey);
  assertThat(response).isNotNull();
  assertThat(response.body().source().readUtf8()).isEqualTo(Utils.INSTANCE.readFileToString(getClass(), fileName));
  response.body().source().close();
}
 
Example #18
Source File: QueryRefetchTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void refetchNoPreCachedQuery() throws Exception {
  CreateReviewMutation mutation = new CreateReviewMutation(
      Episode.EMPIRE,
      ReviewInput.builder().stars(5).commentary("Awesome").favoriteColor(ColorInput.builder().build()).build()
  );

  server.enqueue(Utils.INSTANCE.mockResponse("CreateReviewResponse.json"));
  server.enqueue(Utils.INSTANCE.mockResponse("ReviewsEmpireEpisodeResponse.json"));

  RealApolloCall call = (RealApolloCall) apolloClient.mutate(mutation).refetchQueries(new ReviewsByEpisodeQuery(Episode.EMPIRE));
  Rx2Apollo
      .from(call)
      .test();

  assertThat(server.getRequestCount()).isEqualTo(2);
  Utils.INSTANCE.assertResponse(
      apolloClient.query(new ReviewsByEpisodeQuery(Episode.EMPIRE)).responseFetcher(CACHE_ONLY),
      new Predicate<Response<ReviewsByEpisodeQuery.Data>>() {
        @Override public boolean test(Response<ReviewsByEpisodeQuery.Data> response) throws Exception {
          assertThat(response.data().reviews()).hasSize(3);
          assertThat(response.data().reviews().get(2).stars()).isEqualTo(5);
          assertThat(response.data().reviews().get(2).commentary()).isEqualTo("Amazing");
          return true;
        }
      }
  );
}
 
Example #19
Source File: ApolloParseInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked") InterceptorResponse parse(Operation operation, okhttp3.Response httpResponse)
    throws ApolloHttpException, ApolloParseException {
  String cacheKey = httpResponse.request().header(HttpCache.CACHE_KEY_HEADER);
  if (httpResponse.isSuccessful()) {
    try {
      final OperationResponseParser parser = new OperationResponseParser(operation, responseFieldMapper, scalarTypeAdapters, normalizer);
      final OkHttpExecutionContext httpExecutionContext = new OkHttpExecutionContext(httpResponse);
      Response parsedResponse = parser.parse(httpResponse.body().source());
      parsedResponse = parsedResponse
          .toBuilder()
          .fromCache(httpResponse.cacheResponse() != null)
          .executionContext(parsedResponse.getExecutionContext().plus(httpExecutionContext))
          .build();

      if (parsedResponse.hasErrors() && httpCache != null) {
        httpCache.removeQuietly(cacheKey);
      }
      return new InterceptorResponse(httpResponse, parsedResponse, normalizer.records());
    } catch (Exception rethrown) {
      logger.e(rethrown, "Failed to parse network response for operation: %s", operation);
      closeQuietly(httpResponse);
      if (httpCache != null) {
        httpCache.removeQuietly(cacheKey);
      }
      throw new ApolloParseException("Failed to parse http response", rethrown);
    }
  } else {
    logger.e("Failed to parse network response: %s", httpResponse);
    throw new ApolloHttpException(httpResponse);
  }
}
 
Example #20
Source File: ApolloPrefetchTest.java    From apollo-android with MIT License 5 votes vote down vote up
private void checkCachedResponse(String fileName) throws IOException {
  String cacheKey = lastHttRequest.headers(HttpCache.CACHE_KEY_HEADER).get(0);
  okhttp3.Response response = apolloClient.cachedHttpResponse(cacheKey);
  assertThat(response).isNotNull();
  assertThat(response.body().source().readUtf8()).isEqualTo(Utils.INSTANCE.readFileToString(getClass(), "/" + fileName));
  response.body().source().close();
}
 
Example #21
Source File: WebSocketSubscriptionTransportMessageTest.java    From apollo-android with MIT License 5 votes vote down vote up
MockWebSocket(Request request, WebSocketListener listener) {
  this.request = request;
  this.listener = listener;
  this.listener.onOpen(this, new okhttp3.Response.Builder()
      .request(request)
      .protocol(Protocol.HTTP_1_0)
      .code(200)
      .message("Ok")
      .build()
  );
}
 
Example #22
Source File: IntegrationTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void operationResponseParser() throws Exception {
  String json = Utils.INSTANCE.readFileToString(getClass(), "/HeroNameResponse.json");

  HeroNameQuery query = new HeroNameQuery();
  Response<HeroNameQuery.Data> response = new OperationResponseParser<>(query, query.responseFieldMapper(), new ScalarTypeAdapters(Collections.EMPTY_MAP))
      .parse(new Buffer().writeUtf8(json));

  assertThat(response.data().hero().name()).isEqualTo("R2-D2");
}
 
Example #23
Source File: NormalizedCacheTestCase.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void cacheOnlyMissReturnsNullData() throws Exception {
  Utils.INSTANCE.assertResponse(
      apolloClient.query(new EpisodeHeroNameQuery(Input.fromNullable(Episode.EMPIRE))).responseFetcher(CACHE_ONLY),
      new Predicate<Response<EpisodeHeroNameQuery.Data>>() {
        @Override public boolean test(Response<EpisodeHeroNameQuery.Data> response) throws Exception {
          return response.data() == null;
        }
      }
  );
}
 
Example #24
Source File: Rx2ApolloTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void callIsCanceledWhenDisposed() throws Exception {
  server.enqueue(Utils.INSTANCE.mockResponse(FILE_EPISODE_HERO_NAME_WITH_ID));

  TestObserver<Response<EpisodeHeroNameQuery.Data>> testObserver = new TestObserver<>();
  Disposable disposable = Rx2Apollo
      .from(apolloClient.query(new EpisodeHeroNameQuery(Input.fromNullable(EMPIRE))))
      .subscribeWith(testObserver);

  disposable.dispose();

  testObserver.assertComplete();
  assertThat(testObserver.isDisposed()).isTrue();
}
 
Example #25
Source File: ResponseNormalizationTest.java    From apollo-android with MIT License 5 votes vote down vote up
private <T> void assertHasNoErrors(String mockResponse, Query<?, T, ?> query) throws Exception {
  Utils.INSTANCE.enqueueAndAssertResponse(
      server,
      mockResponse,
      apolloClient.query(query),
      new Predicate<Response<T>>() {
        @Override public boolean test(Response<T> response) throws Exception {
          return !response.hasErrors();
        }
      }
  );
}
 
Example #26
Source File: Rx3ApolloTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void callProducesValue() throws Exception {
  server.enqueue(Utils.INSTANCE.mockResponse(FILE_EPISODE_HERO_NAME_WITH_ID));
  Rx3Apollo
      .from(apolloClient.query(new EpisodeHeroNameQuery(Input.fromNullable(EMPIRE))))
      .test()
      .assertNoErrors()
      .assertComplete()
      .assertValue(new Predicate<Response<EpisodeHeroNameQuery.Data>>() {
        @Override public boolean test(Response<EpisodeHeroNameQuery.Data> response) throws Exception {
          assertThat(response.data().hero().name()).isEqualTo("R2-D2");
          return true;
        }
      });
}
 
Example #27
Source File: Rx2Apollo.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * Converts an {@link ApolloCall} to an {@link Observable}. The number of emissions this Observable will have is based
 * on the {@link com.apollographql.apollo.fetcher.ResponseFetcher} used with the call.
 *
 * @param call the ApolloCall to convert
 * @param <T>  the value type.
 * @return the converted Observable
 * @throws NullPointerException if originalCall == null
 */
@NotNull
@CheckReturnValue
public static <T> Observable<Response<T>> from(@NotNull final ApolloCall<T> call) {
  checkNotNull(call, "call == null");

  return Observable.create(new ObservableOnSubscribe<Response<T>>() {
    @Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
      cancelOnObservableDisposed(emitter, call);
      call.enqueue(new ApolloCall.Callback<T>() {
        @Override public void onResponse(@NotNull Response<T> response) {
          if (!emitter.isDisposed()) {
            emitter.onNext(response);
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }

        @Override public void onStatusEvent(@NotNull ApolloCall.StatusEvent event) {
          if (event == ApolloCall.StatusEvent.COMPLETED && !emitter.isDisposed()) {
            emitter.onComplete();
          }
        }
      });
    }
  });
}
 
Example #28
Source File: ApolloWatcherTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testRefetchCacheControl() throws Exception {
  final List<String> heroNameList = new ArrayList<>();
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();

  ApolloQueryWatcher<EpisodeHeroNameQuery.Data> watcher = apolloClient.query(query).watcher();
  watcher.refetchResponseFetcher(NETWORK_ONLY) //Force network instead of CACHE_FIRST default
      .enqueueAndWatch(
          new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
            @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
              heroNameList.add(response.data().hero().name());
            }

            @Override public void onFailure(@NotNull ApolloException e) {
              Assert.fail(e.getCause().getMessage());
            }
          });

  //A different call gets updated information.
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseNameChange.json"));

  //To verify that the updated response comes from server use a different name change
  // -- this is for the refetch
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseNameChangeTwo.json"));
  apolloClient.query(query).responseFetcher(NETWORK_ONLY).enqueue(null);

  watcher.cancel();
  assertThat(heroNameList.get(0)).isEqualTo("R2-D2");
  assertThat(heroNameList.get(1)).isEqualTo("ArTwo");
  assertThat(heroNameList.size()).isEqualTo(2);
}
 
Example #29
Source File: TestQuery.java    From apollo-android with MIT License 4 votes vote down vote up
@Override
@NotNull
public Response<Optional<TestQuery.Data>> parse(@NotNull final BufferedSource source,
    @NotNull final ScalarTypeAdapters scalarTypeAdapters) throws IOException {
  return SimpleOperationResponseParser.parse(source, this, scalarTypeAdapters);
}
 
Example #30
Source File: TestQuery.java    From apollo-android with MIT License 4 votes vote down vote up
@Override
@NotNull
public Response<Optional<TestQuery.Data>> parse(@NotNull final BufferedSource source) throws
    IOException {
  return parse(source, ScalarTypeAdapters.DEFAULT);
}