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
:
Groovy
1// RxJava2 support
2implementation 'com.apollographql.apollo:apollo-rx2-support:x.y.z'
Usage examples
Converting ApolloCall
to an Observable
Java:
Java
1// Create a query object
2EpisodeHeroName query = EpisodeHeroName.builder().episode(Episode.EMPIRE).build();
3
4// Create an ApolloCall object
5ApolloCall<EpisodeHeroName.Data> apolloCall = apolloClient.query(query);
6
7// RxJava2 Observable
8Observable<Response<EpisodeHeroName.Data>> observable2 = Rx2Apollo.from(apolloCall);
Kotlin:
Kotlin
1// Create a query object
2val query = EpisodeHeroNameQuery(episode = Episode.EMPIRE.toInput())
3
4// Directly create Observable with Kotlin extension
5val observable = apolloClient.rxQuery(query)
Converting ApolloPrefetch
to a Completable
Java:
Java
1//Create a query object
2EpisodeHeroName query = EpisodeHeroName.builder().episode(Episode.EMPIRE).build();
3
4//Create an ApolloPrefetch object
5ApolloPrefetch<EpisodeHeroName.Data> apolloPrefetch = apolloClient.prefetch(query);
6
7//RxJava2 Completable
8Completable completable2 = Rx2Apollo.from(apolloPrefetch);
Kotlin:
Kotlin
1// Create a query object
2val query = EpisodeHeroNameQuery(episode = Episode.EMPIRE.toInput())
3
4// Create Observable for prefetch with Kotlin extension
5val observable = apolloClient.rxPrefetch(query)
Also, don't forget to dispose of your Observer/Subscriber when you are finished:
Java
1Disposable disposable = Rx2Apollo.from(query).subscribe();
2
3//Dispose of your Observer when you are done with your work
4disposable.dispose();
As an alternative, multiple Disposables can be collected to dispose of at once via CompositeDisposable
:
Java
1CompositeDisposable disposable = new CompositeDisposable();
2disposable.add(Rx2Apollo.from(call).subscribe());
3
4// Dispose of all collected Disposables at once
5disposable.clear();
For a concrete example of using Rx wrappers for apollo types, checkout the sample app in the samples
module.