package com.alangpierce.lambdacalculusplayground.drag;

import android.view.MotionEvent;
import android.view.View;

import com.google.common.collect.ImmutableList;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import rx.Observable;
import rx.Subscriber;

public class TouchObservableManagerImpl implements TouchObservableManager {
    private WeakHashMap<View, Observable<MotionEvent>> cachedEventObservables = new WeakHashMap<>();

    @Override
    public Observable<MotionEvent> touchObservableForView(View view) {
        if (!cachedEventObservables.containsKey(view)) {
            final Map<Subscriber<? super MotionEvent>, Void> subscribers =
                    Collections.synchronizedMap(new WeakHashMap<>());
            cachedEventObservables.put(
                    view, Observable.create(observer -> subscribers.put(observer, null)));
            view.setOnTouchListener((v, event) -> {
                // Copy the list of subscribers first, since onNext might end up modifying the list.
                // TODO: Handle unsubscribe and actually unsubscribe when necessary.
                List<Subscriber<? super MotionEvent>> subscriberList =
                        ImmutableList.copyOf(subscribers.keySet());
                for (Subscriber<? super MotionEvent> subscriber : subscriberList) {
                    subscriber.onNext(event);
                }
                return true;
            });
        }
        return cachedEventObservables.get(view);
    }
}

@@ -228,19 +228,19 @@
 va.util.
-Map
+Set
 ;%0Aimport
@@ -264,16 +264,79 @@
 shMap;%0A%0A
+import autovalue.shaded.com.google.common.common.collect.Maps;%0A
 import r
@@ -710,19 +710,19 @@
   final 
-Map
+Set
 %3CSubscri
@@ -749,14 +749,8 @@
 ent%3E
-, Void
 %3E su
@@ -797,41 +797,114 @@
 ons.
-synchronizedMap(new WeakHash
+newSetFromMap(%0A                            Maps.%3CSubscriber%3C? super MotionEvent%3E, Boolean%3EnewConcurrent
 Map
-%3C%3E
 ());
@@ -943,16 +943,40 @@
 les.put(
+view, Observable.create(
 %0A       
@@ -988,22 +988,17 @@
         
-view, 
+(
 Observab
@@ -1004,58 +1004,50 @@
 ble.
-create(observer -%3E subscribers.put(observer, null)
+OnSubscribe%3CMotionEvent%3E) subscribers::add
 ));%0A
@@ -1355,16 +1355,16 @@
 rList =%0A
+
         
@@ -1415,17 +1415,8 @@
 bers
-.keySet()
 );%0A 

Stop using weak references to keep track of subscribers