'Can't get Rocket's EventStream! to work with borrowed values
This is a pretty specific question related to the Rocket crate. I'm not sure if this is an issue with the crate or if I'm just doing something plain wrong. I'm not the best with lifetimes and macros.
I'm trying to setup an SSE connection, and I want the macro to borrow values that are passed into the function.
I initially followed their tutorial for setting up SSEs, and wrote the following code...
#[get("/my/stream")]
pub fn my_stream(config: &State<config::Config>, _pool: &State<Pool<Sqlite>>) -> EventStream![] {
EventStream! {
let mut id = 0;
let mut interval = time::interval(Duration::from_secs(1));
loop {
yield Event::data("test data").event("test").id(id.to_string());
interval.tick().await;
id += 1;
}
}
}
This compiles and works great, but when I try to do something simple and borrow either config or _pool then it complains about the lifetime in the macro. The compiler was pretty clear and it matched what they had in their documentation. So I added the lifetime to the return value.
#[get("/my/stream")]
pub fn my_stream(config: & State<config::Config>, _pool: &State<Pool<Sqlite>>) -> EventStream![Event + '_] {
EventStream! {
let _test = config.database.clone();
let mut id = 0;
let mut interval = time::interval(Duration::from_secs(1));
loop {
yield Event::data("test data").event("test").id(id.to_string());
interval.tick().await;
id += 1;
}
}
}
However, once I do this it complains that Event is not a trait...? I looked through their source and I don't see Event as a trait. What am I doing wrong and why? The last error I receive is...
pub fn my_stream(config: & State<config::Config>, _pool: &State<Pool<Sqlite>>) -> EventStream![Event + '_] {
| ^^^^^ not a trait
|
help: `+` is used to constrain a "trait object" type with lifetimes or auto-traits; structs and enums can't be bound in that way
--> src/api/mod.rs:24:104
This is the output of cargo tree --depth 1
├── clap v2.27.1
├── rocket v0.5.0-rc.1
│ [build-dependencies]
├── serde v1.0.130
├── serde_json v1.0.66
├── sqlx v0.5.9
└── tokio v1.9.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|