简体   繁体   中英

How to automatically update datagrid from IObservable<T>

I use this library https://github.com/step-up-labs/firebase-database-dotnet to retrieve items from firebase, then display it to datagrid in realtime.

But I got stuck when displaying it, based on the link above to get realtime streaming, I need to use this code:

var firebase = new FirebaseClient("https://dinosaur-facts.firebaseio.com/");
var observable = firebase
  .Child("dinosaurs")
  .AsObservable<Dinosaur>()
  .Subscribe(d => Console.WriteLine(d.Key));

I try this code but nothing displayed on the gridview:

var observable = firebase
    .Child("news/item")
    .AsObservable<News>();

disposable = observable.Subscribe();

dataGrid.ItemsSource = observable.AsObservableCollection();

I also try this without any luck:

private ObservableCollection<News> _myItems = new ObservableCollection<News>();
private IEnumerable<News> MyNews { get { return _myItems; } }

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var observable= firebase
        .Child("news/item")
        .AsObservable<News>();

    _myItems = observable.AsObservableCollection();

    disposable = observable.Subscribe();

    dataGrid.ItemsSource = MyNews;
}

Problem is observable callbacks, including modifying ObservableCollection returned by AsObservableCollection , run on thread pool thread by default. But you cannot modify ObservableCollection on non-UI thread, so there is exception which is swallowed. So instead, do it like this:

var observable = firebase
      .Child("news/item")
      .AsObservable<News>();            
dataGrid.ItemsSource = observable
    .ObserveOnDispatcher() // < key point
    .AsObservableCollection();

Don't forget to install nuget package System.Reactive.Windows.Threading and add using System.Reactive.Linq; to access ObserveOnDispatcher extension method.

Also no need to call observable.Subscribe(); , unless of course you need it for other things. AsObservableCollection already subscribes.

@Evk but there`sa problem either with ObserveOnDispatcher() or with datagrid

I have described this problem in this post:

ObserveOnDispatcher duplicates records

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