RxJava2
Apollo Android includes support for RxJava 2.x.
Apollo types can be converted to RxJava2 Observable
types using wrapper functions Rx2Apollo.from(...)
in Java or using extension functions in Kotlin.
Conversion is done according to the following table:
Apollo type | RxJava2 type |
---|---|
ApolloCall<T> | Observable<Response<T>> |
ApolloSubscriptionCall<T> | Flowable<Response<T>> |
ApolloQueryWatcher<T> | Observable<Response<T>> |
ApolloStoreOperation<T> | Single<T> |
ApolloPrefetch | Completable |
Including in your project
Add the following dependency
:
// RxJava2 supportimplementation 'com.apollographql.apollo:apollo-rx2-support:x.y.z'
Usage examples
Converting ApolloCall
to an Observable
Java:
// Create a query objectEpisodeHeroName query = EpisodeHeroName.builder().episode(Episode.EMPIRE).build();// Create an ApolloCall objectApolloCall<EpisodeHeroName.Data> apolloCall = apolloClient.query(query);// RxJava2 ObservableObservable<Response<EpisodeHeroName.Data>> observable2 = Rx2Apollo.from(apolloCall);
Kotlin:
// Create a query objectval query = EpisodeHeroNameQuery(episode = Episode.EMPIRE.toInput())// Directly create Observable with Kotlin extensionval observable = apolloClient.rxQuery(query)
Converting ApolloPrefetch
to a Completable
Java:
//Create a query objectEpisodeHeroName query = EpisodeHeroName.builder().episode(Episode.EMPIRE).build();//Create an ApolloPrefetch objectApolloPrefetch<EpisodeHeroName.Data> apolloPrefetch = apolloClient.prefetch(query);//RxJava2 CompletableCompletable completable2 = Rx2Apollo.from(apolloPrefetch);
Kotlin:
// Create a query objectval query = EpisodeHeroNameQuery(episode = Episode.EMPIRE.toInput())// Create Observable for prefetch with Kotlin extensionval observable = apolloClient.rxPrefetch(query)
Also, don't forget to dispose of your Observer/Subscriber when you are finished:
Disposable disposable = Rx2Apollo.from(query).subscribe();//Dispose of your Observer when you are done with your workdisposable.dispose();
As an alternative, multiple Disposables can be collected to dispose of at once via CompositeDisposable
:
CompositeDisposable disposable = new CompositeDisposable();disposable.add(Rx2Apollo.from(call).subscribe());// Dispose of all collected Disposables at oncedisposable.clear();
For a concrete example of using Rx wrappers for apollo types, checkout the sample app in the samples
module.