Skip to content

Instantly share code, notes, and snippets.

@jgoday
Created October 23, 2019 10:06
Show Gist options
  • Save jgoday/e76deaf462989446b418d87d370b0dbb to your computer and use it in GitHub Desktop.
Save jgoday/e76deaf462989446b418d87d370b0dbb to your computer and use it in GitHub Desktop.
Postgres async notifications with tokio_postgres
#![feature(poll_map)]
use futures::{stream, StreamExt};
use futures::{FutureExt, TryStreamExt};
use std::env;
use tokio::sync::mpsc;
use tokio_postgres::{connect, NoTls};
#[tokio::main]
async fn main() {
let connection_parameters = env::var("DBURL").unwrap();
let (client, mut conn) = connect(&connection_parameters, NoTls)
.await
.unwrap();
let (tx, mut rx) = mpsc::unbounded_channel();
let stream = stream::poll_fn(move |cx| conn.poll_message(cx).map_err(|e| panic!(e)));
let c = stream.forward(tx).map(|r| r.unwrap());
tokio::spawn(c);
println!("After spawn listener");
client.batch_execute("LISTEN test_notifications;").await.unwrap();
loop {
let m = rx.recv().await;
println!("GOT MESSAGE");
}
}