如何在Rust中使用“ flatmap”流?

时间:2019-01-30 13:06:07

标签: stream rust rust-actix

我有一个rusoto_core::ByteStream实现了futures' Stream trait

let chunks = vec![b"1234".to_vec(), b"5678".to_vec()];
let stream = ByteStream::new(stream::iter_ok(chunks));

我想将其传递给actix_web's HttpResponseBuilder::streaming方法。

use actix_web::dev::HttpResponseBuilder; // 0.7.18
use rusoto_core::ByteStream; // 0.36.0

fn example(stream: ByteStream, builder: HttpResponseBuilder) {
    builder.streaming(stream);
}

当我尝试执行此操作时,出现以下错误:

error[E0271]: type mismatch resolving `<rusoto_core::stream::ByteStream as futures::stream::Stream>::Item == bytes::bytes::Bytes`
 --> src/main.rs:5:13
  |
5 |     builder.streaming(stream);
  |             ^^^^^^^^^ expected struct `std::vec::Vec`, found struct `bytes::bytes::Bytes`
  |
  = note: expected type `std::vec::Vec<u8>`
             found type `bytes::bytes::Bytes`

我相信原因是streaming()期望有S: Stream<Item = Bytes, Error>(即Item = Bytes),但是我的ByteStreamItem = Vec<u8>。我该如何解决?

我认为解决方案是以某种方式flatmap我的ByteStream,但我找不到这种流方法。

下面是一个如何使用streaming()的示例:

let text = "123";
let (tx, rx_body) = mpsc::unbounded();
let _ = tx.unbounded_send(Bytes::from(text.as_bytes()));

HttpResponse::Ok()
    .streaming(rx_body.map_err(|e| error::ErrorBadRequest("bad request")))

1 个答案:

答案 0 :(得分:4)

  

如何flatmap在Rust中进行流式播放?

平面图将迭代器的迭代器转换为单个迭代器(或用流代替迭代器)。

Futures 0.1没有直接的平面地图,但是确实有Stream::flatten,可以在Stream::map之后使用。

use futures::{stream, Stream}; // 0.1.25

fn into_many(i: i32) -> impl Stream<Item = i32, Error = ()> {
    stream::iter_ok(0..i)
}

fn nested() -> impl Stream<Item = i32, Error = ()> {
    let stream_of_number = into_many(5);
    let stream_of_stream_of_number = stream_of_number.map(into_many);
    let flat_stream_of_number = stream_of_stream_of_number.flatten();

    // Returns: 0, 0, 1, 0, 1, 2, 0, 1, 2, 3
    flat_stream_of_number
}

但是,这不能解决您的问题

  

streaming()期望有S: Stream<Item = Bytes, Error>(即Item = Bytes),但是我的ByteStreamItem = Vec<u8>

是的,这就是问题所在。通过Bytes::from使用Stream::map将流Item从一种类型转换为另一种类型:

use bytes::Bytes; // 0.4.11
use futures::Stream; // 0.1.25 

fn example(stream: ByteStream, mut builder: HttpResponseBuilder) {
    builder.streaming(stream.map(Bytes::from));
}