@@ -24,15 +24,20 @@ use tokio_postgres::{AsyncMessage, Client, Connection, Notification, Socket};
2424
2525/// Handler for Postgres NOTIFY
2626pub struct Notifier {
27- /// DB client (kept so it's not dropped)
28- #[ allow( unused) ]
29- client : Client ,
3027 /// DB connection
3128 conn : Connection < Socket , NoTlsStream > ,
3229 /// Notification sender
3330 tx : UnboundedSender < Notification > ,
3431}
3532
33+ /// Receiver for Postgres NOTIFY
34+ pub struct Receiver {
35+ /// DB client
36+ client : Client ,
37+ /// Notification receiver
38+ rx : UnboundedReceiver < Notification > ,
39+ }
40+
3641impl Future for Notifier {
3742 type Output = bool ;
3843
@@ -72,18 +77,38 @@ impl Notifier {
7277 }
7378}
7479
75- impl Database {
76- /// Create a new notifier
77- pub async fn notifier (
78- self ,
80+ impl Receiver {
81+ /// Listen for notifications on channels
82+ pub async fn listen (
83+ & self ,
7984 channels : impl Iterator < Item = & str > ,
80- ) -> Result < ( Notifier , UnboundedReceiver < Notification > ) > {
81- let ( client, conn) = self . dedicated_client ( ) . await ?;
82- let ( tx, rx) = unbounded_channel ( ) ;
85+ ) -> Result < ( ) > {
8386 for channel in channels {
84- client. execute ( & format ! ( "LISTEN {channel}" ) , & [ ] ) . await ?;
87+ self . client
88+ . execute ( & format ! ( "LISTEN {channel}" ) , & [ ] )
89+ . await ?;
8590 }
86- let not = Notifier { client, conn, tx } ;
87- Ok ( ( not, rx) )
91+ Ok ( ( ) )
92+ }
93+
94+ /// Receive one notification
95+ pub async fn recv ( & mut self ) -> Option < Notification > {
96+ self . rx . recv ( ) . await
97+ }
98+
99+ /// Check if channel is empty
100+ pub fn is_empty ( & self ) -> bool {
101+ self . rx . is_empty ( )
102+ }
103+ }
104+
105+ impl Database {
106+ /// Create a new notifier / receiver
107+ pub async fn notifier ( self ) -> Result < ( Notifier , Receiver ) > {
108+ let ( client, conn) = self . dedicated_client ( ) . await ?;
109+ let ( tx, rx) = unbounded_channel ( ) ;
110+ let not = Notifier { conn, tx } ;
111+ let rcv = Receiver { client, rx } ;
112+ Ok ( ( not, rcv) )
88113 }
89114}
0 commit comments