I am puzzled by the behavior of the subscribe event in Firebase Realtime Database. I am posting data in firebase which works fine and I am also subscribing to insert/update changes to get the newly added/updated item in the Firebase Realtime Database. However, my subscribe event occurs in any way without inserting/updating anything to the DB.
Here is my MVVM
public ICommand SaveCommand { get; private set; }
public ICommand LoadContentsCommand { get; private set; }
private readonly App CurrentApp;
private readonly IFirebaseDatabaseService firebaseDatabaseService;
public ICommand SaveCommand { get; private set; }
public ICommand LoadContentsCommand { get; private set; }
private readonly App CurrentApp;
private readonly IFirebaseDatabaseService firebaseDatabaseService;
public CommunityHomePageViewModel()
{
firebaseDatabaseService = DependencyService.Get<IFirebaseDatabaseService>();
Title = "Community";
LoadContentsCommand = new Command(async () => await LoadContentsAsync());
SaveCommand = new Command(async () => await SaveDataAsync());
LoadContentsCommand.Execute(null);
CurrentApp = Application.Current as App;
SubscribeToChanges();
}
ObservableCollection<Post> _items;
public ObservableCollection<Post> Items
{
get { return _items; }
set { SetProperty(ref _items, value); }
}
async Task SaveDataAsync()
{
try
{
await firebaseDatabaseService.PostAsync(new Post() { Comment = $"Random comment {new Random().Next(0, 100)}", UserKey = CurrentApp.CurrentUser.Id });
}
catch (Exception e)
{
Logger.LogException(e);
}
}
async Task LoadContentsAsync()
{
try
{
var items = await firebaseDatabaseService.GetItemsAsync(string.Empty);
Items = new ObservableCollection<Post>(items);
}
catch (Exception e)
{
Logger.LogException(e);
}
}
// subscribe occurs just after the items are loaded without waiting for the insert/save to occur.
void SubscribeToChanges()
{
firebaseDatabaseService.Client().Child(nameof(Post))
.AsObservable<Post>()
.Where(post => !Items.Contains(post.Object) && post.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate)
.Subscribe(obs =>
{
Console.WriteLine($"{obs.Key}");
var post = obs.Object;
switch (obs.EventType)
{
case Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate:
Items.Insert(0, post);
break;
}
});
}
and this is the Get method
async Task<IEnumerable<Post>> IFirebaseDatabaseService.GetItemsAsync(string id)
{
if (!_firebaseAuth.IsSignedIn) return null;
if (!string.IsNullOrEmpty(id))
{
return (await _firebaseClient
.Child(typeof(Post).Name)
.OrderByKey()
.StartAt(id)
.LimitToFirst(10)
.OnceAsync<Post>())
.Select(i => new Post
{
Comment = i.Object.Comment,
UserKey = i.Object.UserKey
});
}
return (await _firebaseClient
.Child(typeof(Post).Name)
.OrderByKey()
.LimitToFirst(10)
.OnceAsync<Post>())
.Select(i => new Post
{
Comment = i.Object.Comment,
UserKey = i.Object.UserKey
});
}
Why would the subscribe event even fire before the insert? Am I following the wrong pattern?