Skip to content

Instantly share code, notes, and snippets.

@NorseDreki
Created January 28, 2015 05:34
Show Gist options
  • Save NorseDreki/cb20e26d25308a321732 to your computer and use it in GitHub Desktop.
Save NorseDreki/cb20e26d25308a321732 to your computer and use it in GitHub Desktop.
RxJava's example for Worker
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