2010-06-25 35 views
0

我正在嘗試使用一對Subject類來釋放2組事件序列。該應用程序是一個繪圖應用程序,其中一個主題在用戶點擊時觸發onNext,而另一個主題在用戶雙擊時觸發OnNext。我寫了GetClick & GetDoubleClick方法返回上述情況的可觀察性,並且似乎工作正常。下面的代碼中的問題是,如果在第一個主題上調用onNext來觸發點擊序列,則雙​​擊可觀察事物將永遠不會被調用。如果我在第一個主題上註釋掉onNext調用,那麼雙擊可觀察元素會按預期發射。任何人都可以看看下面的代碼和他們的想法/想法嗎?我已經添加了對以下代碼行問題的評論在Reactive Extensions庫中使用Subject類的幫助

public static KeyValuePair<IObservable<MapPoint>, IObservable<PointCollection>> 
    DrawPointsDynamic(this Map map) 
{ 
    PointCollection pc = new PointCollection(); 
    Subject<Point> ptSubject = new Subject<Point>(); 
    Subject<PointCollection> ptsSubject = new Subject<PointCollection>(); 

    IObservable<Point> ptObs = ptSubject.Hide(); 
    IObservable<PointCollection> ptsObs = ptsSubject.Hide(); 

    map.GetClick() 
     .Subscribe(next => 
      { 
       var p = map.ScreenToMap(next.EventArgs.GetPosition(map)); 
       ptSubject.OnNext(p); //If I leave this line in, the subscription to the doubleClick below does not get called. If comment it out, the subscription below does get called as expected; 
       pc.Add(p); 

      }); 

    map.GetDoubleClick() 
     .Subscribe(next => 
     { 
      ptsSubject.OnNext(pc); 
      pc = new ESRI.ArcGIS.Client.Geometry.PointCollection(); 
     }); 

    KeyValuePair<IObservable<MapPoint>, IObservable<ESRI.ArcGIS.Client.Geometry.PointCollection>> obs = 
     new KeyValuePair<IObservable<MapPoint>, IObservable<ESRI.ArcGIS.Client.Geometry.PointCollection>> 
      (ptObs, ptsObs); 

    return obs; 
} 

另外,我不太確定Hide()的作用。我只是使用它,因爲所有的例子似乎都有。隱藏身份真的意味着什麼?

回答

1

與其試圖解決您現在的問題,我會建議rx-ify一點。第一次迭代是非常簡單的:現在

public static KeyValuePair<IObservable<MapPoint>, IObservable<PointCollection>> 
    DrawPointsDynamic(this Map map) 
{ 
    var pc = new PointCollection(); 
    var ptSubject = map.GetClick().Select(next => map.ScreenToMap(next.EventArgs.GetPosition(map)).Publish(); 
    var ptsSubject = map.GetDoubleClick().Publish(); 

    ptSubject.Subscribe(pc.Add); 
    ptsSubject.Subscribe(_ => pc = new PointCollection()); 

    ptSubject.Connect(); 
    ptsSubject.Connect(); 

    return new KeyValuePair<IObservable<MapPoint>, IObservable<PointCollection>>(ptObs, ptsObs); 
} 

,通過看這個,我懷疑你真正想要的,雖然這是什麼:

public static IObservable<PointCollection> DrawPointsDynamic(this Map map) 
{ 
    var pcs = map.GetDoubleClick().Select(_ => new PointCollection()).Publish(); 
    var ps = map.GetClick().Select(next => map.ScreenToMap(next.EventArgs.GetPosition(map))); 
    var ppcs = pcs.SelectMany(pc => ps.Select(p => { pc.Add(p); return pc; }).TakeUntil(pcs)); 

    var obs = pcs.Merge(ppcs); 

    pcs.Connect(); 

    return obs; 
} 

這將返回一個可觀察會產生點擊或雙擊PointCollection有或沒有點。

相關問題