简体   繁体   中英

Does the Android Data Binding Library hold Strong References on It's Callbacks?

I recently read somewhere that the Data Binding Library would store it's listeners as WeakReferences. Well I couldn't believe it so I took a look at the ObservableArrayMap implementation in the Data Binding Library:

private transient MapChangeRegistry mListeners;

...

@Override
public void addOnMapChangedCallback(
        OnMapChangedCallback<? extends ObservableMap<K, V>, K, V> listener) {
    if (mListeners == null) {
        mListeners = new MapChangeRegistry();
    }
    mListeners.add(listener);
}

The code snipped above points me to the MapChangeRegistry which extends CallbackRegistry :

private List<C> mCallbacks = new ArrayList<C>();

...

public synchronized void add(C callback) {
    if (callback == null) {
        throw new IllegalArgumentException("callback cannot be null");
    }
    int index = mCallbacks.lastIndexOf(callback);
    if (index < 0 || isRemoved(index)) {
        mCallbacks.add(callback);
    }
}

There is a lot going on around, but as I understood the callback is stored inside a List, which tells me if I don't unregister my Callbacks with eg. removeOnMapChangedCallback() I'd risk memory leaks.

My java memory management skills are limited to trust the GC and carefully use WeakReferences (I'd like to improve on that topic someday, when I have the time). But for now I'd like to know if I interpreted my reasearch correctly and that I'd also have to use typical Observer register/unregister boilerplate code when using the Data Binding Library.

The observed items aren't responsible for keeping weak references to the things being notified. Because Observable is an interface, the data binding system can't trust that the implementation uses weak references.

Instead, the observed items are tied back to the generated binding using an intermediate weak reference class to the binding class. It is somewhat complex because of there are so many different types of things to observe, but the implementation is in ViewDataBinding.java and you can see how it is implemented.

Essentially the observing is:

Observed Object ===> Observer - - -> Binding class

where the - - - is the weak reference and === is a strong reference. Because the Observer is a weak reference, it doesn't generate object count overhead that would happen if it had a weak reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM