How can I asynchronously monitor some directories in vala? All I need is for a callback method to be called whenever a file in one of the directories is:
I found GLib.FileMonitor but I am unsure how to use it.
To monitor a directory, you need to first create a GLib.File from that directory by using one of the GLib.File.new_* static methods. new_for_path is probably what you want.
You then need to create a GLib.FileMonitor for that directory using the monitor_directory method of the GLib.File object.
You can then connect to the changed signal of the GLib.FIleMonitor object.
When you compile, you will need to include --pkg gio-2.0
.
Example:
void on_change () {
print("changed\n");
}
void main () {
GLib.File usr_share_applications = File.new_for_path(
"/usr/share/applications"
);
GLib.File local_share_applications = File.new_for_commandline_arg(
GLib.Environment.get_user_data_dir() + "/applications"
);
GLib.FileMonitor mon1;
GLib.FileMonitor mon2;
try {
mon1 = usr_share_applications.monitor_directory(
GLib.FileMonitorFlags.NONE
);
mon1.changed.connect(on_change);
print("Monitoring: "+usr_share_applications.get_path()+"\n");
} catch (GLib.Error e) {
print("Error: "+e.message+"\n");
}
try {
mon2 = local_share_applications.monitor_directory(
GLib.FileMonitorFlags.NONE
);
mon2.changed.connect(on_change);
print("Monitoring: "+local_share_applications.get_path()+"\n");
} catch (GLib.Error e) {
print("Error: "+e.message+"\n");
}
GLib.MainLoop loop = new GLib.MainLoop();
loop.run();
}