androidandroid-fragmentsweakhashmap

WeakHashMap not working as expected in observer pattern


I' am trying to implement observer pattern in Android with WeakHashMap. Here code.

public class DataObservable {
    static WeakHashMap<DataObserver, Class> observers = new WeakHashMap<>();

    public static void addObserver(DataObserver observer, Class dataclass) {
        observers.put(observer, dataclass);
    }

    public static void notifyDataChanged(Class dataclass, Result result) {
        for (Map.Entry<DataObserver, Class> entry : observers.entrySet()) {
            DataObserver observer = entry.getKey();
            Class observerDataClass = entry.getValue();
            if (observerDataClass == dataclass) {
                observer.updateData(dataclass, result);
            }
        }
    }
}


public interface DataObserver {
    void updateData(Class dataclass, Result result);
}

public MyFragment extends Fragment{
    private DataObserver couponsObserver = new DataObserver() {
        @Override
        public void updateData(Class dataclass, Result result) {
            Log.d("d", "sdg");
        }
    } ;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.fragment_sales_coupons, container, false);
       DataObservable.addObserver(couponsObserver, SalesCoupon.class);
        return view;
   }
}

The problem is that then device rotated i expect that weakhashmap observers didnt removed automatically and in create view method added new observers. Thus after first rotation observers contained 2 elements, after next rotation - 3 and so on, though i think it will be only 1. What's wrong?


Solution

  • Ho, i find answer. Changing orientation set all properties of fragment to null, but not necessary remove its from heap, until it do garbage collector. This is why it was not deleted from WeakHashMap. So in order to do this, need run System.gc() on onPause method. Hope it helps somebody :)