- Warum passiert das?
- Ist dies das erwartete Verhalten in Kotlin?
Code: Select all
companion object {
// This lambda IS being garbage collected after a while
val aLambda: (bundle: Bundle?, caller: Fragment?) -> Unit = { _, _ -> if (something()) processRequest() }
// This object IS NOT being garbage collected
val anObject = object: Notifications.Listener {
override fun onNotification(bundle: Bundle?, caller: Fragment?) {
if (something()) processRequest()
}
}
init {
// This Notifications class holds weak references to both the lambda & object the same way
Notifications.addListener(aLambda)
Notifications.addListener(anObject)
}
}
Code: Select all
public class Notifications {
private static ArrayList listenersArray = new ArrayList();
public static void addListener(@NonNull Listener listener) {
listenersArray.add(new WeakReference(listener));
}
public static void notify(@Nullable Bundle bundle, @Nullable Fragment caller) {
for (WeakReference weakListener : listenersArray) {
Listener listener = weakListener.get();
if (listener != null) {
listener.onNotification(bundle, caller);
}
}
}
}