Last active
August 8, 2016 04:38
-
-
Save ronshapiro/9743444 to your computer and use it in GitHub Desktop.
An API client shell that abstracts it's mechanism of executing network calls and provides a simple interface to making the calls using RxJava and Java 8.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package me.ronshapiro.rxjavatest.app; | |
import java.util.concurrent.Executors; | |
import rx.Observable; | |
import rx.Observable.OnSubscribe; | |
import rx.Scheduler; | |
import rx.Subscriber; | |
import rx.Subscription; | |
import rx.android.schedulers.AndroidSchedulers; | |
import rx.functions.Action1; | |
import rx.schedulers.Schedulers; | |
import rx.subjects.PublishSubject; | |
import rx.subjects.Subject; | |
public class RxApiClient { | |
private final Scheduler mScheduler; | |
private final PublishSubject<String> mFeedSubject; | |
private static final boolean ASYNC = false; | |
private int counter = 0; | |
public ApiClient() { | |
mScheduler = Schedulers.executor(Executors.newSingleThreadExecutor()); | |
mFeedSubject = PublishSubject.create(); | |
} | |
public Subscription getFeedAsync(Action1<String> action) { | |
Subscription subscription = mFeedSubject.subscribe(action); | |
Observable<String> feed = Observable.create((Subscriber<? super String> | |
subscriber) -> { | |
subscriber.onNext("emit::" + counter++); | |
}); | |
if (ASYNC) { | |
feed.subscribeOn(mScheduler) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe(mFeedSubject); | |
} else { | |
feed.subscribe(mFeedSubject); | |
} | |
return subscription; | |
} | |
/** | |
* @param action callback to be subscribed to the subject | |
* @param subject event root subject. e.x. All subscribers should listen to events published by | |
* a mFeedSubject even if they created a different action | |
* @param apiCallAction what to do | |
* @return subscription to allow for unsubscribing | |
*/ | |
private <T> Subscription genericApiCall(Action1<T> action, Subject<T, T> subject, | |
OnSubscribe<T> apiCallAction) { | |
Subscription subscription = subject.subscribe(action); | |
Observable<T> composition = Observable.create(apiCallAction); // rename to something better | |
composition.subscribeOn(mScheduler) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe(subject); | |
return subscription; | |
} | |
/** | |
* This is all that would be necessary to add a new network call to the client. | |
*/ | |
public Subscription getFeedSimplified(Action1<String> action) { | |
return genericApiCall(action, mFeedSubject, subscriber -> { | |
JSONObject json = new Api().getFeed(); | |
List<Story> stories = parseFeed(json); | |
subscriber.onNext(stories.get(i)); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment