summaryrefslogtreecommitdiff
path: root/FireBase/ObservableExtensions.cs
blob: bc46261ca79e99547c13236ca6a3e6dd3964183e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.ObjectModel;
using Firebase.Database.Streaming;

namespace Firebase.Database
{
    /// <summary>
    ///     Extensions for <see cref="IObservable{T}" />.
    /// </summary>
    public static class ObservableExtensions
    {
        /// <summary>
        ///     Starts observing on given firebase observable and propagates event into an <see cref="ObservableCollection{T}" />.
        /// </summary>
        /// <param name="observable"> The observable. </param>
        /// <typeparam name="T"> Type of entity. </typeparam>
        /// <returns> The <see cref="ObservableCollection{T}" />. </returns>
        public static ObservableCollection<T> AsObservableCollection<T>(this IObservable<FirebaseEvent<T>> observable)
        {
            var collection = new ObservableCollection<T>();

            observable.Subscribe(f =>
            {
                if (f.EventType == FirebaseEventType.InsertOrUpdate)
                {
                    var i = collection.IndexOf(f.Object);
                    if (i >= 0) collection.RemoveAt(i);

                    collection.Add(f.Object);
                }
                else
                {
                    collection.Remove(f.Object);
                }
            });

            return collection;
        }
    }
}