我在我的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;
}
}发布于 2019-02-18 17:21:41
在.Throttle(TimeSpan.FromMilliseconds(50))之前调用.ObserveOn(new UiContext())可能没有效果,因为Throttle可以更改调度器-每个操作符都可以更改调度器。您应该始终在您希望应用.ObserveOn的接线员或预订呼叫之前执行它。
https://stackoverflow.com/questions/54713877
复制相似问题