当缓冲区大小取决于事件本身,而不仅仅依赖于元素计数或其他一些Observable时,我正在努力缓冲来自Observable的事件。
例如,让我们的事件是字符串,我希望缓冲区不超过一定数量的字符。这是我试图做的,它似乎工作正常,但我不喜欢有状态SizeCounter
可观察。还有更好的办法吗?
public class Test {
static final int MAX_BUFFER_CHARS = 12;
public static void main(String[] args) {
Observable<String> source = Observable.just("item1", "item2", "item3", "item4", "item5");
Observable<String> shared = source.publish().refCount();
Observable<Object> boundarySource = shared.flatMapIterable(new SizeCounter());
Observable<List<String>> buffered = shared.buffer(boundarySource);
for (List<String> strings : buffered.blockingIterable()) {
System.out.println(strings);
}
}
/**
* Emits one-element List if should make a buffer boundary here, and empty List if should continue current buffer.
*/
static class SizeCounter implements Function<String, List<Object>> {
int currentBufferSize = 0;
@Override
public List<Object> apply(String item) throws Exception {
if (currentBufferSize + item.length() > MAX_BUFFER_CHARS) {
// Emit boundary.
currentBufferSize = item.length();
return Collections.singletonList(new Object());
} else {
// Emit nothing.
currentBufferSize += item.length();
return Collections.emptyList();
}
}
}
}
由于平台的限制(不是硬性要求),我更喜欢单线程。无论如何,此代码仅适用于单个线程,因为有状态SizeCounter
。