您正在按定义的模式拆分字节流。我不确定你如何接收你的字节以及你将如何建模你的 observable,Observable<byte> 或Observable<byte[]>!?
无论如何,这里我猜到了字符串的翻译,但想法仍然相同。我选择了x,后跟y 作为模式(在您的情况下为0xFC 0xFA)。
您会在代码中找到我的 cmets:
final ImmutableList<String> PATTERN = ImmutableList.of("x", "y");
Observable<String> source = Observable
.fromArray("x", "y", "1", "2", "3", "x", "y", "4", "5", "x", "y", "1", "x", "y", "x", "4", "6", "x")
.share();//publishing to hot observable (we are splitting this source by some of its elements)
//find the next pattern
Observable<List<String>> nextBoundary = source
.buffer(2, 1)
.filter(pairs -> CollectionUtils.isEqualCollection(PATTERN, pairs));
//https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer2.png
//start a buffer for each x found
//buffers (packets) may overlap
source.buffer(source.filter(e -> e.equals("x")),
x -> source
.take(1)//next emission after the x
.switchMap(y -> y.equals("y") ?
nextBoundary // if 'y' then find the next patter
: Observable.empty() //otherwise stop buffering
)
)
.filter(packet -> packet.size() > 2)//do not take the wrong buffers like ["x", "4"] (x not followed by y) but it is not lost
.map(packet -> {
//each packet is like the following :
//[x, y, 1, 2, 3, x, y]
//[x, y, 4, 5, x, y]
//[x, y, 1, x, y]
//[x, y, x, 4, 6, x]
//because of the closing boundary, the event comes too late
//then we have to handle the packet (it overlaps on the next one)
List<String> ending = packet.subList(packet.size() - 2, packet.size());
return CollectionUtils.isEqualCollection(PATTERN, ending) ? packet.subList(0, packet.size() - 2) : packet;
})
.blockingSubscribe(e -> System.out.println(e));
结果:
[x, y, 1, 2, 3]
[x, y, 4, 5]
[x, y, 1]
[x, y, x, 4, 6, x]