Skip to content

Instantly share code, notes, and snippets.

@digitalbuddha
Last active July 12, 2022 05:18
Show Gist options
  • Save digitalbuddha/3c5bb15fa12a553c85ec to your computer and use it in GitHub Desktop.
Save digitalbuddha/3c5bb15fa12a553c85ec to your computer and use it in GitHub Desktop.
public void readTwice()
{
Observable.fromCallable(() -> {
RedditData inflatedModel = null;
Response response = makeRequest();
String diskValue = null;
try {
File file = new File(getContext().getCacheDir(), "file");
BufferedSink cacheBody = Okio.buffer(Okio.sink(file));
Source cacheWritingSource = treet(response.body().source(), cacheBody);
response = response.newBuilder()
.body(new RealResponseBody(response.headers(), Okio.buffer(cacheWritingSource)))
.build();
InputStreamReader inputStreamReader = new InputStreamReader(response.body().source().inputStream());
inflatedModel = new GsonBuilder()
.create()
.fromJson(inputStreamReader, RedditData.class);
closeAllTheThings(response, cacheBody);
diskValue = Okio.buffer(Okio.source(file)).readUtf8Line();
} catch (Exception e) {
e.printStackTrace();
}
assert diskValue != null;
return inflatedModel;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
}
private Response makeRequest() throws IOException {
Request request = new Request.Builder()
.url("https://www.reddit.com/r/aww/new/.json")
.build();
return new OkHttpClient().newCall(request).execute();
}
private void closeAllTheThings(Response response, BufferedSink cacheBody) throws IOException {
response.body().source().close();
cacheBody.close();
}
public static Source tree(final Source source, final BufferedSink cacheBody)
{
return new Source() {
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead;
try {
bytesRead = source.read(sink, byteCount);
} catch (IOException e) {
throw e;
}
if (bytesRead == -1) {
cacheBody.close(); // The cache response is complete!
return -1;
}
sink.copyTo(cacheBody.buffer(), sink.size() - bytesRead, bytesRead);
cacheBody.emitCompleteSegments();
return bytesRead;
}
@Override
public Timeout timeout() {
return source.timeout();
}
@Override
public void close() throws IOException {
cacheBody.close();
source.close();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment