2016-04-22 100 views
1

問題:我在我的ViewModel中有一個IReactiveDerivedList<SensorViewModel>,並希望訂閱它的更改,包括列表中已有的內容,然後再觀察它。然後將這些數據反饋給Xamarin Android的GoogleMaps。ReactiveUI谷歌地圖

這似乎是工作,當我補充一下:

public void OnMapReady(GoogleMap map) 
{ 
    _itemsAdded = this.ViewModel.Sensors.ItemsAdded 
      .ObserveOn(RxApp.MainThreadScheduler) 
      .Select(s => new CircleOptions() 
       .InvokeCenter(new LatLng(s.Latitude, s.Longitude)) 
       .InvokeRadius(1000) 
       .InvokeFillColor(Color.Blue.ToArgb()) 
       .InvokeStrokeColor(Color.Red.ToArgb())) 
      .Subscribe(
       Observer.Create<CircleOptions>(options => map.AddCircle(options))); 
} 

但我也需要跟蹤從map.AddCircle返回Circle的,所以我可以從地圖當對象消失刪除它。什麼是處理這種情況的被動方式?

回答

1

我不知道這是否是做的最活潑的方式,但我想通一些東西,似乎工作:

private IDisposable _itemsAdded; 
    private IDisposable _itemsRemoved; 

    private readonly Dictionary<string, Circle> _circleMap = new Dictionary<string, Circle>(); 

    public void OnMapReady(GoogleMap map) 
    { 
     _circleMap.Clear(); 

     _itemsAdded = this.ViewModel.Sensors.ItemsAdded 
      .StartWith(this.ViewModel.Sensors) 
      .Subscribe(s => 
      { 
       var options = new CircleOptions() 
        .InvokeCenter(new LatLng(s.Latitude, s.Longitude)) 
        .InvokeRadius(1000) 
        .InvokeFillColor(Color.Blue.ToArgb()) 
        .InvokeStrokeColor(Color.Red.ToArgb()); 

       var circle = map.AddCircle(options); 
       this._circleMap.Add(s.Id, circle); 
      }); 

     _itemsRemoved = this.ViewModel.Sensors.ItemsRemoved 
      .Subscribe(s => 
      { 
       Circle circle = null; 
       if (this._circleMap.TryGetValue(s.Id, out circle)) 
       { 
        this._circleMap.Remove(s.Id); 
        circle.Remove(); 
       } 
      }); 
    } 
+0

這看起來不錯。你也可以考慮使用'CompositeDisposable'來將你的'IDisposable's存儲在一個地方,並用'this.WhenAnyObservable()'直接替換'ViewModel'' - 如果由於某種意外''ViewModel'將會此方法被調用時(或被替換時)爲null。 – pmbanka

+0

我將切換到'CompositeDisposable'。上面的代碼在視圖中(Android Activity)。在這種情況下,我將如何使用'WhenAnyObservable'? – Jeremy

+0

如果你在你的Android項目中引用了ReactiveUI,這應該只是工作,因爲'WhenAny'系列是泛型T的擴展方法。我提到的有關VM的東西也在[老版本的文檔](https:// github。文檔/基礎/ whenany.md#不同,種類-OF-COM whenanys/reactiveui/ReactiveUI/BLOB/e2c01b8230de576e4e7a689828eebfd5193fbf67 /)。 – pmbanka