0

I am having a class extending ReactiveWindowController. As in base class I see this:

// subscribe to listen to window closing
// notification to support (de)activation
NSNotificationCenter
   .DefaultCenter
   .AddObserver(NSWindow.WillCloseNotification, 
       _ => deactivated.OnNext(Unit.Default), this.Window);

Hence in my subclass I am writing the callback to remove the observer, as

public partial class SplitViewWindowController : ReactiveWindowController
{

    ~SplitViewWindowController()
    {
        Console.WriteLine("Destructor of SplitViewWindowController");
    }

    public SplitViewWindowController() : base("SplitViewWindow")
    {
        Console.WriteLine("Constructor of SplitViewWindowController");

        this.Deactivated.Take(1).Subscribe(x => {

           // NSNotificationCenter.DefaultCenter.RemoveObserver(NSWindow.WillCloseNotification);

            // NSNotificationCenter.DefaultCenter.RemoveObserver(this);

            //NSNotificationCenter.DefaultCenter.RemoveObserver(Owner);

        });
    }

But I am lost to find a suitable way to remove the Observer. Or I am doing something wrong here?

Why am I removing the Observer? The answer is this SplitViewController is not dealloc-ed if any observer remains un-registered. I tried with NSWindowController, here if all the observers are removed, the deallocation works and the destructor's logs prints. If I do not remove observer even in case of subclassing from NSWindowController it doesn't call the destructor.

So the fix is to remove the Observer but how?

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140

1 Answers1

2

Save the observer created and then remove and dispose of it when required:

var observer = NSNotificationCenter.DefaultCenter.AddObserver(NSWindow.WillCloseNotification, HandleAction);
// You can also use the helper method...
// var observer = NSWindow.Notifications.ObserveWillClose(HandleEventHandler);

NSNotificationCenter.DefaultCenter.RemoveObserver(observer);
observer.Dispose();
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • 2
    @AnoopVaidya That Reactive code is just wrong, the observer/disposable needs removed and disposed of, thus you have to maintain a ref to it. I use reactiveUI on some projects but have had to modify the source as there are memory leaks through it. – SushiHangover Oct 23 '18 at 15:41
  • Can you please look at the sample, https://www.dropbox.com/s/ckw1ge4snnk45qu/ReactiveReleaseIssue.zip?dl=0 – Anoop Vaidya Oct 23 '18 at 16:33