Skip to content

Instantly share code, notes, and snippets.

@jonathanduty
Created July 12, 2019 11:29
Show Gist options
  • Save jonathanduty/5a53dc3bf4d3c79598675778f56ae843 to your computer and use it in GitHub Desktop.
Save jonathanduty/5a53dc3bf4d3c79598675778f56ae843 to your computer and use it in GitHub Desktop.
Android rxJava
// we use the RxJava2CallAdapterFactory to wrap all of our retrofit api calls in a
// RxJava2 Single
public class BoundAPI {
private static BoundApi sInstance = null;
private final BoundApiService mService;
public static BoundApi getInstance(OkHttpProvider okHttpProvider, GsonProvider gsonProvider) {
if (sInstance == null) {
sInstance = new BoundApi(okHttpProvider, gsonProvider);
}
return sInstance;
}
private BoundApi(OkHttpProvider okHttpProvider, GsonProvider gsonProvider) {
RxJava2CallAdapterFactory callAdapter = getRxAdapter();
GsonConverterFactory converter = getGsonConverter(gsonProvider.getGson());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BoundApiService.Config.BASE_URL)
.addCallAdapterFactory(callAdapter)
.addConverterFactory(converter)
.client(okHttpProvider.getOkHttpClient())
.build();
mService = retrofit.create(BoundApiService.class);
}
public BoundApiService getService() {
return mService;
}
}
public interface BoundApiService {
@GET("v1/community/user/{id}")
Single<UserResponse> getUser(@Path("id") String userId);
}
// then in an activity or fragment where we needed to get a user, we would do that here.
class MyActivity {
@NonNull
private final CompositeDisposable mDisposables;
@Override
public void getUser(@NonNull String userId) {
if (BuildConfig.DEBUG) Log.i(TAG, "getUser: " + userId);
Disposable disposable = mRepository.getUser(userId)
.compose(BaseSchedulerProvider.applySingleSchedulers(mSchedulerProvider))
.doOnSubscribe(__ -> setIsLoading(true))
.doFinally(() -> setIsLoading(false))
.subscribe(this::showUser, this::dispatchError);
mDisposables.add(disposable);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment