![](/img/trans.png)
[英]How to create Observable<Integer> from infinite Stream<Integer> using RxJava2?
[英]How to create an Observable sequence of bytes from an input stream in RxJava
我是RxJava的新手,因此提出了這個問題。 我有一個輸入流,我必須將其轉換為特定大小的字節數組序列。 就像是:
Observable
.just(inputStream)
.map(new Func1<InputStream, Chunk>());
這里Chunk
是一個自定義類,其中包含從流中讀取的字節數。 有人可以幫助我了解如何在RxJava中執行此操作
使用StringObservable.from(InputStream, chunkSize)
從RxJavaString 。 它將返回Observable<byte[]>
並支持背壓(除非下游要求,否則不會從InputStream
讀取)。
順便說一下, Observable.using
可以正確完成關閉資源的操作。 如果Bytes.from(file, chunkSize)
中讀取字節,則可以使用Bytes.from(file, chunkSize)
-extras中的 Bytes.from(file, chunkSize)
在幕后使用Observable.using
)。
您可以先使用Observable.create,再使用flatMap。 請注意,默認情況下,QueuedProducer是無界的,您可以提供包括邊界隊列的自定義實現。
例如:
static class Chunk {
byte[] buf;
int size;
int index;
public Chunk(byte[] buf, int size, int index) {
this.buf = buf;
this.size = size;
this.index = index;
}
}
FileInputStream fis = ...
Observable<Chunk> o = Observable.just(fis).flatMap(new Func1<InputStream, Observable<Chunk>>() {
@Override
public Observable<Chunk> call(InputStream is) {
return Observable.create(new Observable.OnSubscribe<Chunk>() {
public void call(Subscriber<? super Chunk> subscriber) {
final QueuedProducer<Chunk> producer = new QueuedProducer<>(subscriber);
subscriber.setProducer(producer);
try {
int size = 0;
int index = 0;
do {
byte[] buf = new byte[4096];
size = is.read(buf);
if (size > 0) {
Chunk chunk = new Chunk(buf, size, index++);
System.out.println("Producing chunk #" + index + " of size: " + chunk.size);
producer.onNext(chunk);
}
} while (size >= 0);
producer.onCompleted();
} catch (IOException e) {
producer.onError(e);
} finally {
try {
System.out.println("Closing stream");
is.close();
} catch (IOException e) {
}
}
}
})
.subscribeOn(Schedulers.io());
}
});
o.subscribe(new Action1<Chunk>() {
@Override
public void call(Chunk chunk) {
System.out.println("Received chunk #" + chunk.index + " of size: " + chunk.size);
}
});
Thread.sleep(10000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.