Docs
Launch GraphOS Studio
You're viewing documentation for a previous version of this software. Switch to the latest stable version.

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 typeRxJava2 type
ApolloCall<T>Observable<Response<T>>
ApolloSubscriptionCall<T>Flowable<Response<T>>
ApolloQueryWatcher<T>Observable<Response<T>>
ApolloStoreOperation<T>Single<T>
ApolloPrefetchCompletable

Including in your project

Add the following dependency:

// RxJava2 support
implementation 'com.apollographql.apollo:apollo-rx2-support:x.y.z'

Usage examples

Converting ApolloCall to an Observable

Java:

// Create a query object
EpisodeHeroName query = EpisodeHeroName.builder().episode(Episode.EMPIRE).build();
// Create an ApolloCall object
ApolloCall<EpisodeHeroName.Data> apolloCall = apolloClient.query(query);
// RxJava2 Observable
Observable<Response<EpisodeHeroName.Data>> observable2 = Rx2Apollo.from(apolloCall);

Kotlin:

// Create a query object
val query = EpisodeHeroNameQuery(episode = Episode.EMPIRE.toInput())
// Directly create Observable with Kotlin extension
val observable = apolloClient.rxQuery(query)

Converting ApolloPrefetch to a Completable

Java:

//Create a query object
EpisodeHeroName query = EpisodeHeroName.builder().episode(Episode.EMPIRE).build();
//Create an ApolloPrefetch object
ApolloPrefetch<EpisodeHeroName.Data> apolloPrefetch = apolloClient.prefetch(query);
//RxJava2 Completable
Completable completable2 = Rx2Apollo.from(apolloPrefetch);

Kotlin:

// Create a query object
val query = EpisodeHeroNameQuery(episode = Episode.EMPIRE.toInput())
// Create Observable for prefetch with Kotlin extension
val 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 work
disposable.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 once
disposable.clear();

For a concrete example of using Rx wrappers for apollo types, checkout the sample app in the

module.

Previous
Kotlin coroutines
Next
RxJava3
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company