How to check if An observer is still live

Is there a way if I can check if an observer is still reacting on events? I have sometimes observers that still exists but don’t react anymore to sketchup events.

Given an observer instance there is no way to know if it’s receiving notifications. It’s a passive receiver.

No Thomas this is not the answer I was waiting for :frowning:

No?

Maybe we can look at it from a different approach. Why do you need to know this?

Actually there may be. The SketchUp engine calls the instance to ask if it has implemented a callback before it attempts to call the method.

observer.respond_to?(:callback_name)

So what I have done (in the past to see if my callbacks are being called,) is override respond_to?():

alias_method( :has_method?, :respond_to? )
def respond_to?( methname )
  puts "SketchUp is calling #{methname.to_s}"
  has_method?( methname )
end

No guarantee it’d still work in the future. (It is a slow practice. If it were my decision how the observer worked, I’d just call the callback and then trap any NoMethodError exception.)

FYI, we recently found a bug in ModelObserver that would lead to a crash under OSX when overriding respond_to?. We have to change the pattern for the “Safer Observer Events” example due to that. Fixed in the next release but affects all existing versions.

Yea, I do not think I ever wrote it into a plugin. Just used it for debugging. And then only on PC.

But there is a better way of debugging. (That was long before the integrated debugger.)

Another thing that the having the engine use respond_to?() (besides having to make two method calls for every callback,) is that it defeats the idea of a master Observer superclass, that could have common functionality, that is passed down to ALL observer classes.

I have played around with this idea. It is best if this superclass is non-instantiatible. This means it is a mixin module (similar to Kernel,) and is included into all of the APIs observer classes.
In my tests, I named the mixin module Sketchup::Observer.
In addition any coder wanting to create a hybrid “meta” observer class, can simply include the mixin module in their class as well.

The common functionality defined in the mixin module would be attach_to() method that inserts attachment references into a collection of objects that the observer is attached to. There would be dettach_from() and dettach_all() methods. And query methods attachments() and attached_to?(obj), etc. In some cases, like AppObserver subclasses, there can be only one attached object, so no collection in that case.

The module can also have a module function that returns an array of class names that are subclasses of Sketchup::Observer (ie, classes that mixin the functionality module.) This could be used for debugging, etc.

1 Like