使用ReactiveUI的可分页实时搜索

时间:2019-10-17 14:06:18

标签: xamarin.forms reactiveui

当我的视图需要可分页时,我有一个添加到ViewModel中的接口

public interface IPageable
{
    Task LoadNextPage();
    bool IsLoadingPage { get; set; }
}

然后我将PageableBehavior附加到ListView上,并且只要ListView到达页面底部,它就会在ViewModel上调用IPageable.LoadNextPage();。 (注意:当不使用ReactiveUI时,我已经完成了所有这些工作)

我的问题是,尽管我可以轻松地对搜索词做出反应,但我似乎无法弄清楚如何也以反应式方式将下一页加载到_searchResults中。

public class SeedSelectionViewModel : ReactiveObject, IPageable
{
    private const int PageSize = 30;
    private const int Threshold = 3;
    private static readonly TimeSpan _throttle = TimeSpan.FromMilliseconds(200);
    private readonly ISeedInputDataService _dataService;
    private readonly ObservableAsPropertyHelper<IEnumerable<SeedVarietySeed>> _searchResults;

    public SeedSelectionViewModel(ISeedInputDataService dataService)
    {
        _dataService = dataService;

        this.WhenAnyValue(x => x.SearchText)
            .Throttle(_throttle)
            .Select(term => term?.Trim())
            .DistinctUntilChanged()
            .Where(term => !string.IsNullOrWhiteSpace(term) && term.Trim().Length >= Threshold)
            .SelectMany((searchText,count,token) => SearchSeedVarieties(searchText,0))
            .ObserveOn(RxApp.MainThreadScheduler)
            .ToProperty(this, nameof(SearchResults), out _searchResults);
    }

    [Reactive] public string SearchText { get; set; }

    [Reactive] public bool IsLoadingPage { get; set; }

    public IEnumerable<SeedVarietySeed> SearchResults => _searchResults.Value;

    private Task<IEnumerable<SeedVarietySeed>> SearchSeedVarieties(string searchText, int skip) 
        => _dataService.FindSeedVarieties(searchText, skip, PageSize, CancellationToken.None);

    public Task LoadNextPage()
    {
        // how do I load additional results into _searchResults?
        return Task.CompletedTask;
    }
}

1 个答案:

答案 0 :(得分:1)

这里的问题是您不能以这种方式使用ObservableAsPropertyHelper。您不能通过两个不同的订阅进行更改。

处理该问题的正确方法是使用ObservableCollection<T>或类似名称,然后从InvokeCommand调用WhenAnyValue

ctor()
{
    _loadDataCommand = ReactiveCommand.CreateFromTask<string>(LoadData);

    this.WhenAnyValue(x => x.SearchText)
            .Throttle(_throttle)
            .Select(term => term?.Trim())
            .DistinctUntilChanged()
            .Where(term => !string.IsNullOrWhiteSpace(term) && term.Trim().Length >= Threshold)
            .ObserveOn(RxApp.MainThreadScheduler)
            .InvokeCommand(_loadDataCommand);
}

private async Task LoadData(string searchText)
{
    var result = await _dataService.FindSeedVarieties(searchText, 0, PageSize, CancellationToken.None).ConfigureAwait(true);
    SearchResults.ReplaceRange(result);
}