我在ios项目中使用System.Reactive,并且我知道我需要使用ObserveOn来指定在哪个线程上执行订阅服务器。但是我似乎无法正常工作。
就我所知,这应该是可行的,还是我执行错了?
public class UiContext : IScheduler
{
/// <inheritdoc />
public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
NSOperationQueue.MainQueue.AddOperation(() => action(this, state));
return Disposable.Empty;
}
/// <inheritdoc />
public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
NSOperationQueue.MainQueue.AddOperation(() => action(this, state));
return Disposable.Empty;
}
/// <inheritdoc />
public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
{
NSOperationQueue.MainQueue.AddOperation(() => action(this, state));
return Disposable.Empty;
}
/// <inheritdoc />
public DateTimeOffset Now { get; }
}
void SomeMethod()
{
WhenValidationChanged
.ObserveOn(new UiContext())
.SubscribeOn(new UiContext())
.Throttle(TimeSpan.FromMilliseconds(50))
.Subscribe(OnValidationChanged);
}
private void OnValidationChanged(object obj)
{
if (TableView.DataSource is InfoFieldsDataSource dataSource)
{
var validationErrors = dataSource.Items.OfType<InfoFieldViewModelBase>().Count(d => !d.IsValid);
// Exception is raised about not being executed on UI thread
_validationController.View.BackgroundColor = validationErrors > 0 ? UIColor.Green : UIColor.Red;
}
}
答案 0 :(得分:2)
在.ObserveOn(new UiContext())
之前调用.Throttle(TimeSpan.FromMilliseconds(50))
可能无效,因为Throttle
可以更改调度程序-每个操作员都可以更改调度程序。您应该始终在希望将其应用于话务员或预订呼叫之前进行.ObserveOn
。