Created
January 28, 2015 05:34
-
-
Save NorseDreki/cb20e26d25308a321732 to your computer and use it in GitHub Desktop.
RxJava's example for Worker
This file contains hidden or 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
public static Observable<String> generateJson(long id, int delay, int itemSize, int numItems) { | |
return Observable.create((Subscriber<? super String> subscriber) -> { | |
Worker worker = Schedulers.computation().createWorker(); | |
subscriber.add(worker); | |
worker.schedule(() -> { | |
try { | |
StringWriter jsonString = new StringWriter(); | |
JsonGenerator json = jsonFactory.createJsonGenerator(jsonString); | |
json.writeStartObject(); | |
// manipulate the ID such that we can know the response is from the server (client will know the logic) | |
long responseKey = getResponseKey(id); | |
json.writeNumberField("responseKey", responseKey); | |
json.writeNumberField("delay", delay); | |
if (itemSize > MAX_ITEM_LENGTH) { | |
throw new IllegalArgumentException("itemSize can not be larger than: " + MAX_ITEM_LENGTH); | |
} | |
json.writeNumberField("itemSize", itemSize); | |
json.writeNumberField("numItems", numItems); | |
json.writeArrayFieldStart("items"); | |
for (int i = 0; i < numItems; i++) { | |
json.writeString(RAW_ITEM_LONG.substring(0, itemSize)); | |
} | |
json.writeEndArray(); | |
json.writeEndObject(); | |
json.close(); | |
subscriber.onNext(jsonString.toString()); | |
subscriber.onCompleted(); | |
} catch (Exception e) { | |
subscriber.onError(e); | |
} | |
}, delay, TimeUnit.MILLISECONDS); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment