com.apollographql.apollo.ApolloCall Java Examples

The following examples show how to use com.apollographql.apollo.ApolloCall. 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: 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 #3
Source File: BaseCommand.java    From twitch4j with MIT License 6 votes vote down vote up
/**
 * Run Command
 *
 * @return T
 */
@Override
protected T run() {
    // Run GraphQL Call
    getGraphQLCall().enqueue(new ApolloCall.Callback<T>() {
        @Override
        public void onResponse(@NotNull Response<T> response) {
            if (response.errors().size() > 0) {
                throw new RuntimeException("GraphQL API: " + response.errors().toString());
            }

            resultData = response.data();
        }

        @Override
        public void onFailure(@NotNull ApolloException e) {
            throw new RuntimeException(e);
        }
    });

    // block until we've got a result
    block();
    return resultData;
}
 
Example #4
Source File: RealApolloQueryWatcher.java    From apollo-android with MIT License 6 votes vote down vote up
synchronized Optional<ApolloCall.Callback<T>> terminate() {
  switch (state.get()) {
    case ACTIVE:
      tracker.unregisterQueryWatcher(this);
      state.set(TERMINATED);
      return Optional.fromNullable(originalCallback.getAndSet(null));
    case CANCELED:
      return Optional.fromNullable(originalCallback.getAndSet(null));
    case IDLE:
    case TERMINATED:
      throw new IllegalStateException(
          CallState.IllegalStateMessage.forCurrentState(state.get()).expected(ACTIVE, CANCELED));
    default:
      throw new IllegalStateException("Unknown state");
  }
}
 
Example #5
Source File: RealApolloQueryWatcher.java    From apollo-android with MIT License 6 votes vote down vote up
private synchronized void activate(Optional<ApolloCall.Callback<T>> callback) throws ApolloCanceledException {
  switch (state.get()) {
    case IDLE:
      originalCallback.set(callback.orNull());
      tracker.registerQueryWatcher(this);
      break;
    case CANCELED:
      throw new ApolloCanceledException();
    case TERMINATED:
    case ACTIVE:
      throw new IllegalStateException("Already Executed");
    default:
      throw new IllegalStateException("Unknown state");
  }
  state.set(ACTIVE);
}
 
Example #6
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 #7
Source File: QueryReFetcher.java    From apollo-android with MIT License 6 votes vote down vote up
private void refetchQueries() {
  final OnCompleteCallback completeCallback = onCompleteCallback;
  final AtomicInteger callsLeft = new AtomicInteger(calls.size());
  for (final RealApolloCall call : calls) {
    //noinspection unchecked
    call.enqueue(new ApolloCall.Callback() {
      @Override public void onResponse(@NotNull Response response) {
        if (callsLeft.decrementAndGet() == 0 && completeCallback != null) {
          completeCallback.onFetchComplete();
        }
      }

      @Override public void onFailure(@NotNull ApolloException e) {
        if (logger != null) {
          logger.e(e, "Failed to fetch query: %s", call.operation);
        }

        if (callsLeft.decrementAndGet() == 0 && completeCallback != null) {
          completeCallback.onFetchComplete();
        }
      }
    });
  }
}
 
Example #8
Source File: Rx2Apollo.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 #9
Source File: QueryRefetchTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void refetchWatchers() throws Exception {
  server.enqueue(Utils.INSTANCE.mockResponse("ReviewsEmpireEpisodeResponse.json"));
  server.enqueue(Utils.INSTANCE.mockResponse("CreateReviewResponse.json"));
  server.enqueue(Utils.INSTANCE.mockResponse("ReviewsEmpireEpisodeResponseUpdated.json"));

  final AtomicReference<Response<ReviewsByEpisodeQuery.Data>> empireReviewsWatchResponse = new AtomicReference<>();
  ApolloQueryWatcher<ReviewsByEpisodeQuery.Data> queryWatcher = apolloClient.query(new ReviewsByEpisodeQuery(Episode.EMPIRE))
      .watcher()
      .refetchResponseFetcher(NETWORK_FIRST)
      .enqueueAndWatch(new ApolloCall.Callback<ReviewsByEpisodeQuery.Data>() {
        @Override public void onResponse(@NotNull Response<ReviewsByEpisodeQuery.Data> response) {
          empireReviewsWatchResponse.set(response);
        }

        @Override public void onFailure(@NotNull ApolloException e) {
        }
      });

  CreateReviewMutation mutation = new CreateReviewMutation(
      Episode.EMPIRE,
      ReviewInput.builder().stars(5).commentary("Awesome").favoriteColor(ColorInput.builder().build()).build()
  );
  Rx2Apollo
      .from(apolloClient.mutate(mutation).refetchQueries(queryWatcher.operation().name()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(3);

  Response<ReviewsByEpisodeQuery.Data> empireReviewsQueryResponse = empireReviewsWatchResponse.get();
  assertThat(empireReviewsQueryResponse.data().reviews()).hasSize(4);
  assertThat(empireReviewsQueryResponse.data().reviews().get(3).stars()).isEqualTo(5);
  assertThat(empireReviewsQueryResponse.data().reviews().get(3).commentary()).isEqualTo("Awesome");

  queryWatcher.cancel();
}
 
Example #10
Source File: RealApolloQueryWatcher.java    From apollo-android with MIT License 5 votes vote down vote up
synchronized Optional<ApolloCall.Callback<T>> responseCallback() {
  switch (state.get()) {
    case ACTIVE:
    case CANCELED:
      return Optional.fromNullable(originalCallback.get());
    case IDLE:
    case TERMINATED:
      throw new IllegalStateException(
          CallState.IllegalStateMessage.forCurrentState(state.get()).expected(ACTIVE, CANCELED));
    default:
      throw new IllegalStateException("Unknown state");
  }
}
 
Example #11
Source File: RealApolloQueryWatcher.java    From apollo-android with MIT License 5 votes vote down vote up
@Override public ApolloQueryWatcher<T> enqueueAndWatch(@Nullable final ApolloCall.Callback<T> callback) {
  try {
    activate(Optional.fromNullable(callback));
  } catch (ApolloCanceledException e) {
    if (callback != null) {
      callback.onCanceledError(e);
    } else {
      logger.e(e, "Operation: %s was canceled", operation().name().name());
    }
    return this;
  }
  activeCall.enqueue(callbackProxy());
  return this;
}
 
Example #12
Source File: ApolloCallTracker.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * <p>Removes provided {@link ApolloCall} that finished his execution, if it is found, else throws an
 * {@link AssertionError}.</p>
 * <p>
 * If the removal operation is successful and no active running calls are found, then the registered
 * {@link ApolloCallTracker#idleResourceCallback} is invoked.
 *
 * <p><b>Note</b>: This method needs to be called right after an apolloCall is completed (whether successful or
 * failed).</p>
 */
void unregisterCall(@NotNull ApolloCall call) {
  checkNotNull(call, "call == null");
  Operation operation = call.operation();
  if (operation instanceof Query) {
    unregisterQueryCall((ApolloQueryCall) call);
  } else if (operation instanceof Mutation) {
    unregisterMutationCall((ApolloMutationCall) call);
  } else {
    throw new IllegalArgumentException("Unknown call type");
  }
}
 
Example #13
Source File: ApolloCallTracker.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * <p>Adds provided {@link ApolloCall} that is currently in progress.</p>
 *
 * <p><b>Note</b>: This method needs to be called right before an apolloCall is executed.</p>
 */
void registerCall(@NotNull ApolloCall call) {
  checkNotNull(call, "call == null");
  Operation operation = call.operation();
  if (operation instanceof Query) {
    registerQueryCall((ApolloQueryCall) call);
  } else if (operation instanceof Mutation) {
    registerMutationCall((ApolloMutationCall) call);
  } else {
    throw new IllegalArgumentException("Unknown call type");
  }
}
 
Example #14
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 #15
Source File: Rx3Apollo.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 #16
Source File: ApolloIdlingResourceTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void checkIsIdleNow_whenCallIsWatched() 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).watcher().enqueueAndWatch(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 #17
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 #18
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));
            });
}
 
Example #19
Source File: CommandFollowUser.java    From twitch4j with MIT License 5 votes vote down vote up
@Override
protected ApolloCall getGraphQLCall() {
    ApolloCall apolloCall = apolloClient.mutate(
        FollowMutation.builder()
            .followUserInput(
                FollowUserInput.builder()
                    .targetID(targetUserId.toString())
                    .disableNotifications(goLiveNotification ? false : true)
                    .build()
            )
            .build()
    );

    return apolloCall;
}
 
Example #20
Source File: CommandUnfollowUser.java    From twitch4j with MIT License 5 votes vote down vote up
@Override
protected ApolloCall getGraphQLCall() {
    ApolloCall apolloCall = apolloClient.mutate(
        UnfollowMutation.builder()
            .unfollowUserInput(
                UnfollowUserInput.builder()
                    .targetID(targetUserId.toString())
                    .build()
            )
            .build()
    );

    return apolloCall;
}
 
Example #21
Source File: BaseFetcherTest.java    From apollo-android with MIT License 4 votes vote down vote up
@Override public void onStatusEvent(@NotNull ApolloCall.StatusEvent event) {
  if (event == ApolloCall.StatusEvent.COMPLETED) {
    if (completed) throw new IllegalStateException("onCompleted already called Do not reuse tracking callback.");
    completed = true;
  }
}
 
Example #22
Source File: BaseCommand.java    From twitch4j with MIT License 2 votes vote down vote up
/**
 * Abstract GraphQL Call
 *
 * @return ApolloCall
 */
protected abstract ApolloCall getGraphQLCall();