Skip to content

[FEATURE REQUEST] Receive D-Bus signals as stream #1820

@swsnr

Description

@swsnr

Currently, gio::DBusConnection only offers signal_subscribe and signal_unsubscribe to receive D-Bus signals, which isn't that convenient, and I find myself defining some abstractions around this in every Rust project, to handle signal lifetime more conveniently and on top of that to receive signal emissions as a stream instead of dealing with callbacks, e.g.

#[derive(Debug)]
pub struct SignalSubscription {
    bus: WeakRef<gio::DBusConnection>,
    id: Option<SignalSubscriptionId>,
}

impl SignalSubscription {
    fn new(bus: &gio::DBusConnection, id: SignalSubscriptionId) -> Self {
        Self {
            bus: bus.downgrade(),
            id: Some(id),
        }
    }
}

impl Drop for SignalSubscription {
    fn drop(&mut self) {
        if let Some(connection) = self.bus.upgrade()
            && let Some(id) = self.id.take()
        {
            connection.signal_unsubscribe(id);
        }
    }
}

and then something like

 /// Receive emissions of a D-Bus signal as stream.
    fn receive_signal<S: AsRef<str>, T: FromVariant + 'static + Send>(
        &self,
        sender: Option<&str>,
        interface_name: Option<&str>,
        member: Option<&str>,
        object_path: Option<&str>,
        arg0: Option<S>,
        flags: DBusSignalFlags,
    ) -> impl Stream<Item = T>;

implemented on top of mpsc::channel and the above SignalSubscription to create a stream from signal emissions, with the lifetime of the signal subscription coupled to the lifetime of the stream, and with automatic variant conversion of signal parameters.

Would this be a reasonable and desired extension to gio::DBusConnection? If so, I'll prepare a pull request, but I can also understand if it's not something you'd like to maintain; in this I'll just keep it in my local utility library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions