com.apollographql.apollo.rx2.Rx2Apollo Java Examples

The following examples show how to use com.apollographql.apollo.rx2.Rx2Apollo. 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: 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 #3
Source File: HttpCacheTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void cacheStaleBeforeNetwork() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(1);

  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()).httpCachePolicy(HttpCachePolicy.NETWORK_FIRST))
      .test();

  assertThat(server.getRequestCount()).isEqualTo(2);
  assertThat(lastHttResponse.networkResponse()).isNotNull();
  assertThat(lastHttResponse.cacheResponse()).isNull();
  checkCachedResponse("/HttpCacheTestAllPlanets.json");
}
 
Example #4
Source File: HttpCacheTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void cacheStaleBeforeNetworkError() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(1);

  server.enqueue(new MockResponse().setResponseCode(504).setBody(""));
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery())
      .httpCachePolicy(HttpCachePolicy.NETWORK_FIRST))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(2);
  assertThat(lastHttResponse.networkResponse()).isNotNull();
  assertThat(lastHttResponse.cacheResponse()).isNotNull();
  checkCachedResponse("/HttpCacheTestAllPlanets.json");
}
 
Example #5
Source File: HttpCacheTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void cacheStale() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(1);

  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(2);
  assertThat(lastHttResponse.networkResponse()).isNotNull();
  assertThat(lastHttResponse.cacheResponse()).isNull();
  checkCachedResponse("/HttpCacheTestAllPlanets.json");
}
 
Example #6
Source File: ApolloCancelCallTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void cancelCallAfterEnqueueNoCallback() throws Exception {
  OkHttpClient okHttpClient = new OkHttpClient.Builder()
      .dispatcher(new Dispatcher(Utils.INSTANCE.immediateExecutorService()))
      .build();
  apolloClient = ApolloClient.builder()
      .serverUrl(server.url("/"))
      .okHttpClient(okHttpClient)
      .httpCache(new ApolloHttpCache(cacheStore, null))
      .build();
  server.enqueue(mockResponse("EpisodeHeroNameResponse.json"));
  final ApolloCall<EpisodeHeroNameQuery.Data> call = apolloClient.query(new EpisodeHeroNameQuery(Input.fromNullable(Episode.EMPIRE)));

  final TestObserver<Response<EpisodeHeroNameQuery.Data>> test = Rx2Apollo.from(call)
      .test();
  call.cancel();
  test
      .awaitDone(1, TimeUnit.SECONDS)
      .assertNoErrors()
      .assertNoValues()
      .assertNotComplete();
}
 
Example #7
Source File: ApolloInterceptorTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void asyncApplicationInterceptorThrowsApolloException() throws Exception {
  final String message = "ApolloException";
  EpisodeHeroNameQuery query = createHeroNameQuery();
  ApolloInterceptor interceptor = new ApolloInterceptor() {
    @Override
    public void interceptAsync(@NotNull InterceptorRequest request, @NotNull ApolloInterceptorChain chain,
        @NotNull Executor dispatcher, @NotNull CallBack callBack) {
      ApolloException apolloException = new ApolloParseException(message);
      callBack.onFailure(apolloException);
    }

    @Override public void dispose() {

    }
  };

  client = createApolloClient(interceptor);
  Rx2Apollo.from(client.query(query))
      .test()
      .assertError(new Predicate<Throwable>() {
        @Override public boolean test(Throwable throwable) throws Exception {
          return message.equals(throwable.getMessage()) && throwable instanceof ApolloParseException;
        }
      });
}
 
Example #8
Source File: AsyncNormalizedCacheTestCase.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void testAsync() throws IOException, InterruptedException, ApolloException {
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();

  for (int i = 0; i < 500; i++) {
    server.enqueue(mockResponse("HeroNameResponse.json"));
  }

  List<Observable<Response<EpisodeHeroNameQuery.Data>>> calls = new ArrayList<>();
  for (int i = 0; i < 1000; i++) {
    ApolloQueryCall<EpisodeHeroNameQuery.Data> queryCall = apolloClient
        .query(query)
        .responseFetcher(i % 2 == 0 ? ApolloResponseFetchers.NETWORK_FIRST : ApolloResponseFetchers.CACHE_ONLY);
    calls.add(Rx2Apollo.from(queryCall));
  }
  TestObserver<Response<EpisodeHeroNameQuery.Data>> observer = new TestObserver<>();
  Observable.merge(calls).subscribe(observer);
  observer.awaitTerminalEvent();
  observer.assertNoErrors();
  observer.assertValueCount(1000);
  observer.assertNever(new Predicate<Response<EpisodeHeroNameQuery.Data>>() {
    @Override public boolean test(Response<EpisodeHeroNameQuery.Data> dataResponse) throws Exception {
      return dataResponse.hasErrors();
    }
  });
}
 
Example #9
Source File: ApolloExceptionTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void httpException() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(401).setBody("Unauthorized request!"));

  final AtomicReference<Throwable> errorRef = new AtomicReference<>();
  final AtomicReference<String> errorResponse = new AtomicReference<>();
  Rx2Apollo
      .from(apolloClient.query(emptyQuery))
      .doOnError(new Consumer<Throwable>() {
        @Override public void accept(Throwable throwable) throws Exception {
          errorRef.set(throwable);
          errorResponse.set(((ApolloHttpException) throwable).rawResponse().body().string());
        }
      })
      .test()
      .awaitDone(timeoutSeconds, TimeUnit.SECONDS)
      .assertError(ApolloHttpException.class);

  ApolloHttpException e = (ApolloHttpException) errorRef.get();
  assertThat(e.code()).isEqualTo(401);
  assertThat(e.message()).isEqualTo("Client Error");
  assertThat(errorResponse.get()).isEqualTo("Unauthorized request!");
  assertThat(e.getMessage()).isEqualTo("HTTP 401 Client Error");
}
 
Example #10
Source File: HttpCacheTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void cacheAfterDelete() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  checkCachedResponse("/HttpCacheTestAllPlanets.json");

  cacheStore.delegate.delete();

  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery())
      .httpCachePolicy(HttpCachePolicy.CACHE_FIRST))
      .test();
  checkCachedResponse("/HttpCacheTestAllPlanets.json");

  assertThat(server.getRequestCount()).isEqualTo(2);
}
 
Example #11
Source File: HttpCacheTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void cacheNonStale() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  assertThat(server.takeRequest()).isNotNull();
  checkCachedResponse("/HttpCacheTestAllPlanets.json");

  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery())
      .httpCachePolicy(HttpCachePolicy.CACHE_FIRST))
      .test();

  assertThat(server.getRequestCount()).isEqualTo(1);
  assertThat(lastHttResponse.networkResponse()).isNull();
  assertThat(lastHttResponse.cacheResponse()).isNotNull();
}
 
Example #12
Source File: ApolloExceptionTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void testParseException() throws Exception {
  server.enqueue(new MockResponse().setBody("Noise"));
  Rx2Apollo
      .from(apolloClient.query(emptyQuery))
      .test()
      .awaitDone(timeoutSeconds, TimeUnit.SECONDS)
      .assertNoValues()
      .assertError(new Predicate<Throwable>() {
        @Override public boolean test(Throwable throwable) throws Exception {
          ApolloParseException e = (ApolloParseException) throwable;
          assertThat(e.getMessage()).isEqualTo("Failed to parse http response");
          assertThat(e.getCause().getClass()).isEqualTo(JsonEncodingException.class);
          return true;
        }
      });
}
 
Example #13
Source File: HttpCacheTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void noCacheStore() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");

  ApolloClient apolloClient = ApolloClient.builder()
      .serverUrl(server.url("/"))
      .okHttpClient(new OkHttpClient.Builder()
          .addInterceptor(new TrackingInterceptor())
          .dispatcher(new Dispatcher(Utils.INSTANCE.immediateExecutorService()))
          .build())
      .dispatcher(Utils.INSTANCE.immediateExecutor())
      .build();

  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();
        }
      });
  checkNoCachedResponse();
}
 
Example #14
Source File: ApolloPrefetchTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void prefetchFileSystemWriteFailure() throws IOException {
  FaultyHttpCacheStore faultyCacheStore = new FaultyHttpCacheStore(FileSystem.SYSTEM);
  cacheStore.delegate = faultyCacheStore;

  faultyCacheStore.failStrategy(FaultyHttpCacheStore.FailStrategy.FAIL_HEADER_WRITE);
  server.enqueue(Utils.INSTANCE.mockResponse("HttpCacheTestAllPlanets.json"));

  Rx2Apollo.from(apolloClient.prefetch(new AllPlanetsQuery()))
      .test()
      .assertError(Exception.class);
  checkNoCachedResponse();

  server.enqueue(Utils.INSTANCE.mockResponse("HttpCacheTestAllPlanets.json"));
  faultyCacheStore.failStrategy(FaultyHttpCacheStore.FailStrategy.FAIL_BODY_WRITE);
  Rx2Apollo.from(apolloClient.prefetch(new AllPlanetsQuery()))
      .test()
      .assertError(Exception.class);
  checkNoCachedResponse();
}
 
Example #15
Source File: ApolloCallTrackerTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void testIdleCallBackIsInvokedWhenApolloClientBecomesIdle() throws InterruptedException, TimeoutException {
  server.enqueue(createMockResponse());
  final AtomicBoolean idle = new AtomicBoolean();
  IdleResourceCallback idleResourceCallback = new IdleResourceCallback() {
    @Override public void onIdle() {
      idle.set(true);
    }
  };
  apolloClient.idleCallback(idleResourceCallback);

  assertThat(idle.get()).isFalse();
  Rx2Apollo
      .from(apolloClient.query(EMPTY_QUERY))
      .test()
      .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS);
  assertThat(idle.get()).isTrue();
}
 
Example #16
Source File: GitHuntEntryDetailActivity.java    From apollo-android with MIT License 6 votes vote down vote up
private void fetchRepositoryDetails() {
  ApolloCall<EntryDetailQuery.Data> entryDetailQuery = application.apolloClient()
      .query(new EntryDetailQuery(repoFullName))
      .responseFetcher(ApolloResponseFetchers.CACHE_FIRST);

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

        @Override public void onError(Throwable e) {
          Log.e(TAG, e.getMessage(), e);
        }

        @Override public void onComplete() {

        }
      }));
}
 
Example #17
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void cacheOnlyMiss() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");

  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery())
      .httpCachePolicy(HttpCachePolicy.CACHE_ONLY))
      .test()
      .assertError(ApolloHttpException.class);
}
 
Example #18
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void networkOnly_responseWithGraphError_noCached() throws Exception {
  enqueueResponse("/ResponseError.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()).httpCachePolicy(HttpCachePolicy.NETWORK_ONLY))
      .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 #19
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void fileSystemUnavailable() throws IOException, ApolloException {
  cacheStore.delegate = new DiskLruHttpCacheStore(new NoFileSystem(), new File("/cache/"), Integer.MAX_VALUE);
  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();
        }
      });
  checkNoCachedResponse();
}
 
Example #20
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void cacheUpdate() throws Exception {
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(1);
  checkCachedResponse("/HttpCacheTestAllPlanets.json");

  enqueueResponse("/HttpCacheTestAllPlanets2.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(2);
  checkCachedResponse("/HttpCacheTestAllPlanets2.json");
  assertThat(lastHttResponse.networkResponse()).isNotNull();
  assertThat(lastHttResponse.cacheResponse()).isNull();

  enqueueResponse("/HttpCacheTestAllPlanets2.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery())
      .httpCachePolicy(HttpCachePolicy.CACHE_FIRST))
      .test();

  assertThat(server.getRequestCount()).isEqualTo(2);
  assertThat(lastHttResponse.networkResponse()).isNull();
  assertThat(lastHttResponse.cacheResponse()).isNotNull();
  checkCachedResponse("/HttpCacheTestAllPlanets2.json");
}
 
Example #21
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 #22
Source File: ApolloExceptionTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void httpExceptionPrefetch() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(401).setBody("Unauthorized request!"));
  Rx2Apollo
      .from(apolloClient.prefetch(emptyQuery))
      .test()
      .awaitDone(timeoutSeconds, TimeUnit.SECONDS)
      .assertNoValues()
      .assertError(ApolloHttpException.class);
}
 
Example #23
Source File: ApolloExceptionTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void testTimeoutException() throws Exception {
  Rx2Apollo
      .from(apolloClient.query(emptyQuery))
      .test()
      .awaitDone(timeoutSeconds * 2, TimeUnit.SECONDS)
      .assertNoValues()
      .assertError(new Predicate<Throwable>() {
        @Override public boolean test(Throwable throwable) throws Exception {
          ApolloNetworkException e = (ApolloNetworkException) throwable;
          assertThat(e.getMessage()).isEqualTo("Failed to execute http call");
          assertThat(e.getCause().getClass()).isEqualTo(SocketTimeoutException.class);
          return true;
        }
      });
}
 
Example #24
Source File: ApolloExceptionTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void testTimeoutExceptionPrefetch() throws Exception {
  Rx2Apollo
      .from(apolloClient.prefetch(emptyQuery))
      .test()
      .awaitDone(timeoutSeconds * 2, TimeUnit.SECONDS)
      .assertNoValues()
      .assertError(new Predicate<Throwable>() {
        @Override public boolean test(Throwable throwable) throws Exception {
          ApolloNetworkException e = (ApolloNetworkException) throwable;
          assertThat(e.getMessage()).isEqualTo("Failed to execute http call");
          assertThat(e.getCause().getClass()).isEqualTo(SocketTimeoutException.class);
          return true;
        }
      });
}
 
Example #25
Source File: ApolloCallTrackerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testRunningCallsCountWhenSyncPrefetchCallIsMade() throws InterruptedException {
  assertThat(apolloClient.activeCallsCount()).isEqualTo(0);
  Rx2Apollo
      .from(apolloClient.prefetch(EMPTY_QUERY))
      .test()
      .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS);
  assertThat(activeCallCounts).isEqualTo(Collections.singletonList(1));
  assertThat(apolloClient.activeCallsCount()).isEqualTo(0);
}
 
Example #26
Source File: ApolloCallTrackerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testRunningCallsCountWhenAsyncPrefetchCallIsMade() throws InterruptedException {
  assertThat(apolloClient.activeCallsCount()).isEqualTo(0);
  server.enqueue(createMockResponse());
  Rx2Apollo
      .from(apolloClient.prefetch(EMPTY_QUERY))
      .test()
      .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS);
  assertThat(activeCallCounts).isEqualTo(Collections.singletonList(1));
  assertThat(apolloClient.activeCallsCount()).isEqualTo(0);
}
 
Example #27
Source File: ApolloCallTrackerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testRunningCallsCountWhenAsyncApolloCallIsMade() throws InterruptedException {
  assertThat(apolloClient.activeCallsCount()).isEqualTo(0);
  server.enqueue(createMockResponse());
  Rx2Apollo
      .from(apolloClient.query(EMPTY_QUERY))
      .test()
      .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS);
  assertThat(activeCallCounts).isEqualTo(Collections.singletonList(1));
  assertThat(apolloClient.activeCallsCount()).isEqualTo(0);
}
 
Example #28
Source File: GitHuntEntryDetailActivity.java    From apollo-android with MIT License 5 votes vote down vote up
private void subscribeRepoCommentAdded() {
  ApolloSubscriptionCall<RepoCommentAddedSubscription.Data> subscriptionCall = application.apolloClient()
      .subscribe(new RepoCommentAddedSubscription(repoFullName));

  disposables.add(Rx2Apollo.from(subscriptionCall)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(
          new DisposableSubscriber<Response<RepoCommentAddedSubscription.Data>>() {
            @Override public void onNext(Response<RepoCommentAddedSubscription.Data> response) {
                final RepoCommentAddedSubscription.Data data = response.data();
                if (data != null) {
                    RepoCommentAddedSubscription.CommentAdded newComment = data.commentAdded();
                    if (newComment != null) {
                        commentsListViewAdapter.addItem(newComment.content());
                    } else {
                        Log.w(TAG, "Comment added subscription data is null.");
                    }
                    Toast.makeText(GitHuntEntryDetailActivity.this, "Subscription response received", Toast.LENGTH_SHORT)
                            .show();
                }
            }

            @Override public void onError(Throwable e) {
              Log.e(TAG, e.getMessage(), e);
              Toast.makeText(GitHuntEntryDetailActivity.this, "Subscription failure", Toast.LENGTH_SHORT).show();
            }

            @Override public void onComplete() {
              Log.d(TAG, "Subscription exhausted");
              Toast.makeText(GitHuntEntryDetailActivity.this, "Subscription complete", Toast.LENGTH_SHORT).show();
            }
          }
      )
  );
}
 
Example #29
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 #30
Source File: OverviewViewModel.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
private void loadPinnedRepos() {
    pinnedState.setValue(State.loading(null));
    ApolloCall<GetPinnedReposQuery.Data> apolloCall = apolloClient.query(GetPinnedReposQuery.builder()
                    .login(user)
                    .build());
    RxHelper.getObservable(Rx2Apollo.from(apolloCall))
            .filter(dataResponse -> !dataResponse.hasErrors())
            .flatMap(dataResponse -> {
                GetPinnedReposQuery.Data data = dataResponse.data();
                if (data != null && data.user() != null) {
                    return Observable.fromIterable(data.user().pinnedRepositories().edges());
                }
                return Observable.empty();
            })
            .map(GetPinnedReposQuery.Edge::node)
            .toList()
            .toObservable()
            .subscribe(nodes1 -> {
                pinnedNodes.setValue(nodes1);
                if (nodes1.size() > 0) {
                    pinnedState.setValue(State.success(null));
                } else {
                    pinnedState.setValue(State.error(null));
                }
            }, throwable -> {
                throwable.printStackTrace();
                pinnedState.setValue(State.error(null));
            });
}