首页 > 解决方案 > 在java9中将发布者流到字符串

问题描述

我怎样才能得到一个字符串Flow.Publisher<Byte> body?我只想解析来自 Publisher 的字符串。

标签: javarx-java

解决方案


这就是你可以用RxJava2做到这一点的方法:

Flow.Publisher<Byte> bytes = ...;

Flowable.fromPublisher(
        FlowAdapters.toPublisher(
            bytes
        )
    ).toList()
        .map(byteList -> new String(convert(byteList)))
        .subscribe((String string) -> {
            System.out.println(string);
        });

转换定义如下:

   static byte[] convert(List<Byte> list) {
        final byte[] bytes = new byte[list.size()];
        int idx = 0;
        for (byte b : list) {
            bytes[idx] = b;
            idx++;
        }
        return bytes;
    }

推荐阅读