1

I would like to buffer an image from BLE notification. I get 20 bytes long array in every notification. (There is 15-20ms pause between notifications.) They come in sequence, and I can recognise the first and the last package of the image. Images is coming one after another.

My problem is I don't know how to implement it in RxJava2. I have a very poor solution as you see below. It is working, but sometimes image sending has interrupted, so I didn't get the last package, and new image mix with old one.

I would like to buffer depend of byte array's value, from the first package to the last package.

Observable<byte[]> obs = notificationObservable()
.map(notification -> {
    return notification.getBytes();
});

disposables.add(notificationObservable()
.map(notification -> {
    return notification.getBytes();
})
.buffer(obs.delay(10, TimeUnit.MILLISECONDS)
    .filter(bytes -> {
        return bytes[2] < 0; //last package
    })
)
.map(bytes -> new MyImage(bytes))
.subscribe(
    imageSubject::onNext,
    imageSubject::onError,
    imageSubject::onComplete));
Szelk Baltazár
  • 363
  • 2
  • 9

1 Answers1

1

What I usually do in cases like this is to prepare a builder class that handles the parts.

See the following example:

class ImageBuilder {

    private final List<byte[]> parts = new ArrayList<>();

    public ImageBuilder append(byte[] part) {
        if (!isReady()) {
            parts.add(part);
            return this;
        } else {
            ImageBuilder builder = new ImageBuilder();
            return builder.append(part);
        }
    }

    public boolean isReady() {
        byte[] part = parts.get(parts.size() - 1);
        return part[2] < 0;
    }

    public MyImage build() {
        // take the parts and build your image
        return MyImage.buildFrom(parts);
    }

}

Then you can use it like this:

Observable<byte[]> bytePartObservable = ...;

Observable<MyImage> images = bytePartObservable
    .scan(new ImageBuilder(), ImageBuilder::append)
    .filter(ImageBuilder::isReady)
    .map(ImageBuilder::build);

images.subscribe( ... )
ESala
  • 6,878
  • 4
  • 34
  • 55