Skip to content

Instantly share code, notes, and snippets.

@jsaund
Last active May 9, 2023 10:50
Show Gist options
  • Select an option

  • Save jsaund/c4dae07c6778bb17e57a7bcf95ed37bf to your computer and use it in GitHub Desktop.

Select an option

Save jsaund/c4dae07c6778bb17e57a7bcf95ed37bf to your computer and use it in GitHub Desktop.
Read files reactively using RxJava
public Observable<byte[]> readFile(@NonNull FileInputStream stream) {
final SyncOnSubscribe<FileInputStream, byte[]> fileReader = SyncOnSubscribe.createStateful(
() -> stream,
(stream, output) -> {
try {
final byte[] buffer = new byte[BUFFER_SIZE];
int count = stream.read(buffer);
if (count < 0) {
output.onCompleted();
} else {
output.onNext(buffer);
}
} catch (IOException error) {
output.onError(error);
}
return stream;
},
s -> IOUtil.closeSilently(s));
return Observable.create(fileReader);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment