Sve*_*dos 4 c# system.reactive
我将事件(按钮的分页事件)转换为IObservable,并异步接收来自服务的结果。
作为副作用,我必须更新子视图。我有两种解决方案:
选择中的副作用:
//Converting events to a "stream" of search results.
IObservable<SearchResult> resultsFromPageChange = Observable.FromEventPattern<EventArgs>(this,
"PageChangedEvent")
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(async ev =>
{
var input = new SearchResultInput()
{
PageSize = PageSize,
PageIndex = PageIndex,
SearchOptions = _currentSearchOptions,
SearchText = SearchText.Value
};
var result = await GetPagedComponents(input);
//Side effect
ActivateAttributesView(result.Components.FirstOrDefault());
return result;
}).Switch(); //flatten and take most recent.
Run Code Online (Sandbox Code Playgroud)在subsribe中做副作用:
//Converting events to a "stream" of search results.
IObservable<SearchResult> resultsFromPageChange = Observable.FromEventPattern<EventArgs>(this,
"PageChangedEvent")
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(async ev =>
{
var input = new SearchResultInput()
{
PageSize = PageSize,
PageIndex = PageIndex,
SearchOptions = _currentSearchOptions,
SearchText = SearchText.Value
};
return await GetPagedComponents(input);
}).Switch(); //flatten and take most recent.
//Do side effect in the subscribe
resultsFromPageChange.Subscribe(x =>
{
if (x != null)
ActivateAttributesView(x.Components.FirstOrDefault());
});
Run Code Online (Sandbox Code Playgroud)两种方法都有效。我应该选择哪种解决方案,为什么?
谢谢。
因为有一个疑问,为什么它根本不能产生值,所以下面是完整的代码:
//Converting events to a "stream" of search results.
IObservable<SearchResult> resultsFromPageChange = Observable.FromEventPattern<EventArgs>(this,
"PageChangedEvent")
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(async ev =>
{
var input = new SearchResultInput()
{
PageSize = PageSize,
PageIndex = PageIndex,
SearchOptions = _currentSearchOptions,
SearchString = SearchString.Value
};
return await SearchComponentsPaged(input);
}).Switch(); //flatten and take most recent.
SearchString = new ReactiveProperty<string>(""); //Bound to TextBox.Text
//Create a "stream" of search results from a string given by user (SearchString)
SearchResult = SearchString
.SetValidateNotifyError(s => _componentDataService.ValidateSearchStringLength(s).Errors)
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(async term =>
{
var input = new SearchResultInput()
{
PageSize = PageSize,
PageIndex = PageIndex,
SearchOptions = _currentSearchOptions,
SearchString = term
};
return await SearchComponentsPaged(input);
})
.Switch()
.Merge(resultsFromPageChange) //Merge the result of paging and text changing.
.ToReactiveProperty();
//Update Attributes view
SearchResult.Subscribe(searchResult =>
{
if (searchResult != null)
{
ActivateAttributesView(searchResult.Components.FirstOrDefault());
SearchResult.Value.TotalItemsCount = searchResult.TotalItemsCount;
}
});
Run Code Online (Sandbox Code Playgroud)
它的实际作用是,当搜索字符串更改并获取分页结果时,向数据库发送搜索请求,或者在收到PageChangedEvent时使用相同的搜索字符串获取另一个页面。.Merge(...)是否订阅?