I am developing a Xamarin.Forms app. It have SearchBar in the NavigationBar, ListView in the ContentPage and a Entry with AddButton in the bottom. When user click on the AddButton the text in the Entry adds to the realm mobile database. Which autorefresh the IEnumerable. The ListView that is bind to IEnumerable auto updates.
public class MainViewModel : ReactiveObject
{
public IEnumerable<Company> Companies { get; set; }
[Reactive]
public string Query { get; set; }
public string NewCompany { get; set; }
public ReactiveCommand<Unit, Unit> AddCompanyCommand { get; set; }
public ReactiveCommand<Unit, IEnumerable<Company>> SearchCommand { get; set; }
Realm _realm;
public MainViewModel()
{
_realm = Realm.GetInstance();
Companies = _realm.All<Company>();
AddCompanyCommand = ReactiveCommand.CreateFromTask(async () => await AddButtonClicked());
SearchCommand = ReactiveCommand.Create<Unit, IEnumerable<Company>>(
_ =>
SortCollection()
);
SearchCommand.ToProperty(this, nameof(Companies));
this.WhenAnyValue(x => x.Query).Throttle(TimeSpan.FromSeconds(1)).Select(_ => Unit.Default).InvokeCommand(this, x => x.SearchCommand);
}
async Task AddButtonClicked()
{
if (!string.IsNullOrWhiteSpace(NewCompany))
{
_realm.Write(() =>
{
_realm.Add(new Company { Name = NewCompany });
});
NewCompany = string.Empty;
}
}
IEnumerable<Company> SortCollection()
{
if (string.IsNullOrWhiteSpace(Query))
{
Companies = Companies.Where(x => x.Name != string.Empty);
}
else
{
Companies = Companies.Where(x => x.Name.IndexOf(Query, StringComparison.InvariantCultureIgnoreCase) >= 0);
}
return Companies;
}
}
Recently when I added Search Logic to the ViewModel the ListView is not Auto Updating. I either have to search or restart the app to display the new item in the ListView. When I comment out the following line the ListView starts auto updating.
SearchCommand.ToProperty(this, nameof(Companies));
But then it stops displaying Search Results. I want both Auto updating with new item and displaying search result functionalities in the ListView.