Pros and Cons of Listeners as WeakReferences

前端 未结 12 1043
天命终不由人
天命终不由人 2020-12-04 12:18

What are the pros and cons of keeping listeners as WeakReferences.

The big \'Pro\' of course is that:

Adding a listener as a WeakReference means the listener

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 12:45

    Because you are adding WeakReference listener, I'm assuming, you are using a custom Observable object.

    It makes perfect sense to use a WeakReference to an object in the following situation. - There is a list of listeners in Observable object. - You already have a hard reference to the listeners somewhere else. (you'd have to be sure of this) - You don't want the garbage collector to stop clearing the listeners just because there is a reference to it in the Observable. - During garbage collection the listeners will be cleared up. In the method where you notify the listeners, you clear up the WeakReference objects from the notification list.

提交回复
热议问题