vala Signals Basic signal


Example

Signals are only available to GObject classes. They can only be public, which means that any part of the code can connect handlers and trigger them.

public class Emitter : Object {
    // A signal is declared like a method,
    // but with the signal keyword.
    public signal void my_signal ();

    public void send_signal () {
        this.my_signal (); // Send a signal by calling it like a method.
    }
}

void main () {
    var emitter = new Emitter ();
    // Use the connect method of the signal to add an handler.
    emitter.my_signal.connect (() => {
        print ("Received the signal.\n");
    });
    emitter.send_signal ();
    emitter.my_signal (); // You can send a signal from anywhere.
}

You can also use normal functions as handlers if they have the same signature as the signal.

void main () {
    var emitter = new Emitter ();
    emitter.connect (my_handler);
    emitter.my_signal ();
}

void my_handler () {
    print ("Received the signal.\n");
}