我有一个队列(碰巧是Kafka,但我不确定这是否重要),我从中阅读消息。我想创建一个流来表示这个数据。
使用(kafka)队列的伪代码如下所示:
List<Message> messages = new ArrayList<>();
while (true) {
ConsumerRecords<String, Message> records = kafkaConsumer.poll(100);
messages.add(recordsToMessages(records));
if (x) {
break;
}
}
return messages.stream();
使用此伪代码,在while循环中断之前(即,在读取所有队列之前),不会返回流。
我希望能够直接返回流,也就是说,在流返回后可以向流中添加新消息。
我觉得我需要使用stream.generate,但我不确定如何使用,或者我需要一个spliterator?
我还想在代码中的稍后点关闭流。
谢谢!
1条答案
按热度按时间cvxl0en21#
下面是一个注解示例,说明了如何进行此操作:
.
这个代码背后的想法是,你可以养活一个
Stream
通过习俗Iterator
,本身从外部源提取数据。数据从外部源传输到
Iterator
通过Queue
. 因为只有你知道你的数据是什么样子的,以及如何检测到已经没有剩余的数据可以读取了,所以决定流是否应该继续被输入的过程被提取到一个用户提供的函数中。希望有帮助?