本文整理汇总了C#中ReplaySubject.OnCompleted方法的典型用法代码示例。如果您正苦于以下问题:C# ReplaySubject.OnCompleted方法的具体用法?C# ReplaySubject.OnCompleted怎么用?C# ReplaySubject.OnCompleted使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ReplaySubject
的用法示例。
在下文中一共展示了ReplaySubject.OnCompleted方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateDownloadObservable
private static IObservable<byte[]> CreateDownloadObservable(Uri uri)
{
return Observable.Create<byte[]>(o => {
var result = new ReplaySubject<byte[]>();
var inner = Observable.Using(() => new WebClient(), wc => {
var obs = Observable
.FromEventPattern<
DownloadDataCompletedEventHandler,
DownloadDataCompletedEventArgs>(
h => wc.DownloadDataCompleted += h,
h => wc.DownloadDataCompleted -= h)
.Take(1);
wc.DownloadDataAsync(uri);
return obs;
}).Subscribe(ep => {
if (ep.EventArgs.Cancelled) {
result.OnCompleted();
} else {
if (ep.EventArgs.Error != null) {
result.OnError(ep.EventArgs.Error);
} else {
result.OnNext(ep.EventArgs.Result);
result.OnCompleted();
}
}
}, ex => {
result.OnError(ex);
});
return new CompositeDisposable(inner, result.Subscribe(o));
}).Retry(5);
}
示例2: Start
private void Start()
{
//ReplaySubjectも初期を設定することができる(今回は設定しない)
replaySubject = new ReplaySubject<int>();
/*
OnNextを何回か繰り返す → Subscribe と実行し、Subscribeした瞬間に過去の値がまとめて値が発行されることを確認しよう
*/
// Subscribeボタンが押されたらSubjectをSubscribeしてresultTextに表示する
subscribeButton.OnClickAsObservable().Subscribe(_ =>
{
if (replaySubject != null)
{
replaySubject.Subscribe(
time => resultText.text += time.ToString() + " ", //OnNext
() => resultText.text += "OnCompleted "); //OnCompleted
}
});
// OnNextボタンが押されたら今が何度目のOnNextであるかを発行する
onNextButton.OnClickAsObservable().Subscribe(_ =>
{
if (replaySubject != null)
{
replaySubject.OnNext(++onNextCount);
}
});
// OnCompletedボタンが押されたらOnCompletedを発行する
onCompletedButton.OnClickAsObservable().Subscribe(_ =>
{
if (replaySubject != null)
{
replaySubject.OnCompleted();
}
});
// Resetボタンが押されたら全体を初期化する
resetButton.OnClickAsObservable().Subscribe(_ =>
{
if (replaySubject != null)
{
replaySubject.OnCompleted();
}
replaySubject = new ReplaySubject<int>();
resultText.text = "";
onNextCount = 0;
});
}
示例3: UsingSubject
static IObservable<string> UsingSubject()
{
var subject = new ReplaySubject<string>();
subject.OnNext("a");
subject.OnNext("b");
subject.OnCompleted();
Task.Delay(TimeSpan.FromMilliseconds(3000)).Wait();
return subject;
}
示例4: BlockingMethod
///<summary>
///The Method simulates a blocking call by assigning the Immediate Thread as the Thread of execution
/// The execution will move into asyncmode when we call the Nonblocking Method
/// </summary>
private static IObservable<string> BlockingMethod()
{
var subject = new ReplaySubject<string>(Scheduler.Immediate);
subject.Subscribe(Console.WriteLine);
subject.OnNext("a");
subject.OnNext("b");
subject.OnCompleted();
Thread.Sleep(2000);
return subject;
}
示例5: Returns_Correct_Movement
public static async Task Returns_Correct_Movement(decimal price1, decimal price2, PriceMovement expected)
{
var subject = new ReplaySubject<IPrice>();
var result = subject.ToPriceMovementStream();
subject.OnNext(new Price { Mid = price1 });
subject.OnNext(new Price { Mid = price2 });
subject.OnCompleted();
// Assert
await result.SingleAsync(movement => movement == expected);
}
示例6: buffer_size_includes_oncompleted
public void buffer_size_includes_oncompleted()
{
ReplaySubject<int> subject = new ReplaySubject<int>(2);
StatsObserver<int> stats = new StatsObserver<int>();
subject.OnNext(1);
subject.OnNext(2);
subject.OnNext(3);
subject.OnCompleted();
subject.Subscribe(stats);
Assert.AreEqual(1, stats.NextCount);
Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 3 }));
Assert.IsTrue(stats.CompletedCalled);
}
示例7: Factory
private IObservable<ManagementBaseObject> Factory(ManagementClass mc)
{
var src = new ReplaySubject<ManagementBaseObject>();
var ob = new ManagementOperationObserver();
Observable.FromEventPattern<ObjectReadyEventHandler, ObjectReadyEventArgs>(
h => h.Invoke,
h => ob.ObjectReady += h,
h => ob.ObjectReady -= h
).Subscribe(obj => src.OnNext(obj.EventArgs.NewObject));
Observable.FromEventPattern<CompletedEventHandler, CompletedEventArgs>(
h => h.Invoke,
h => ob.Completed += h,
h => ob.Completed -= h
).Subscribe(_ => src.OnCompleted());
mc.GetInstances(ob);
return src.AsObservable();
}
示例8: CallOperationOnService
private static IObservable<ServiceState> CallOperationOnService(ServiceBase serviceBase, Operation operation)
{
ReplaySubject<ServiceState> result = new ReplaySubject<ServiceState>();
result.OnNext(operation.InitialState);
var methodObs = Observable.Start(() =>
{
Type serviceBaseType = serviceBase.GetType();
object[] parameters = null;
if (operation == Operations.Start)
{
parameters = new object[] { null };
}
try
{
serviceBaseType.InvokeMember(operation.MethodCall, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, serviceBase, parameters);
}
catch (Exception ex)
{
throw new Exception(string.Format("An exception was thrown while trying to call the {0} of the {1} service. Examine the inner exception for more information.", operation, serviceBase.ServiceName), ex.InnerException);
}
});
methodObs.Subscribe
(
_ =>
{
result.OnNext(operation.FinishedState);
result.OnCompleted();
},
ex =>
{
result.OnNext(operation.ErrorState);
result.OnError(ex);
}
);
return result;
}
示例9: ReadsSegment
public void ReadsSegment()
{
var stream = CreateStream("2012-03-05 13:56:12;warn;Program;\"Test message\";TextException\r\n");
var format = new CsvLogFormat {
ReadHeader = false,
Delimeter = ';',
FieldCount = 5
};
var subject = new ReplaySubject<RecordSegment>();
format.ReadSegments(subject, stream, CancellationToken.None).Wait();
subject.OnCompleted();
var segment = subject.ToEnumerable().FirstOrDefault();
Assert.Equal(0, segment.Offset);
Assert.Equal(stream.Length, segment.Length);
}
示例10: sends_live_values_after_replay
public void sends_live_values_after_replay()
{
ReplaySubject<int> subject = new ReplaySubject<int>();
StatsObserver<int> stats = new StatsObserver<int>();
subject.OnNext(1);
subject.OnNext(2);
subject.Subscribe(stats);
subject.OnNext(3);
subject.OnCompleted();
Assert.AreEqual(3, stats.NextCount);
Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 1, 2, 3 }));
Assert.IsTrue(stats.CompletedCalled);
}
示例11: ReplaySubjectBufferReplay
public void ReplaySubjectBufferReplay()
{
var subject = new ReplaySubject<int>(bufferSize: 3);
var onNext = new List<int>();
var exception = new List<Exception>();
int onCompletedCallCount = 0;
var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
subject.OnNext(1);
subject.OnNext(10);
subject.OnNext(100);
subject.OnNext(1000);
subject.OnNext(10000);
onNext.Is(100, 1000, 10000); // cut 1, 10
// replay subscription
onNext.Clear();
_.Dispose();
subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
onNext.Is(100, 1000, 10000);
subject.OnNext(20000);
onNext.Is(1000, 10000, 20000);
subject.OnCompleted();
onCompletedCallCount.Is(1);
}
示例12: Completed_to_late_subscriber_ReplayOne
public void Completed_to_late_subscriber_ReplayOne()
{
var s = new ReplaySubject<int>(1);
s.OnNext(1);
s.OnNext(2);
s.OnCompleted();
var scheduler = new TestScheduler();
var observer = scheduler.CreateObserver<int>();
s.Subscribe(observer);
Assert.AreEqual(2, observer.Messages.Count);
Assert.AreEqual(2, observer.Messages[0].Value.Value);
Assert.AreEqual(NotificationKind.OnCompleted, observer.Messages[1].Value.Kind);
}
示例13: ExpiredIndexClearsItems
public async Task ExpiredIndexClearsItems()
{
var expected = 5;
var username = "octocat";
var reponame = "repo";
var cache = new InMemoryBlobCache();
var apiClient = Substitute.For<IApiClient>();
var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
var user = CreateOctokitUser(username);
apiClient.GetUser().Returns(Observable.Return(new UserAndScopes(user, null)));
apiClient.GetOrganizations().Returns(Observable.Empty<Organization>());
var act = modelService.GetAccounts().ToEnumerable().First().First();
var repo = Substitute.For<ILocalRepositoryModel>();
repo.Name.Returns(reponame);
repo.CloneUrl.Returns(new UriString("https://github.com/" + username + "/" + reponame));
var indexKey = string.Format(CultureInfo.InvariantCulture, "{0}|{1}:{2}", CacheIndex.PRPrefix, user.Login, repo.Name);
var prcache = Enumerable.Range(1, expected)
.Select(id => CreatePullRequest(user, id, ItemState.Open, "Cache " + id, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow));
// seed the cache
prcache
.Select(item => new ModelService.PullRequestCacheItem(item))
.Select(item => item.Save<ModelService.PullRequestCacheItem>(cache, indexKey).ToEnumerable().First())
.SelectMany(item => CacheIndex.AddAndSaveToIndex(cache, indexKey, item).ToEnumerable())
.ToList();
// expire the index
var indexobj = await cache.GetObject<CacheIndex>(indexKey);
indexobj.UpdatedAt = DateTimeOffset.UtcNow - TimeSpan.FromMinutes(6);
await cache.InsertObject(indexKey, indexobj);
var prlive = Observable.Range(5, expected)
.Select(id => CreatePullRequest(user, id, ItemState.Open, "Live " + id, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 0))
.DelaySubscription(TimeSpan.FromMilliseconds(10));
apiClient.GetPullRequestsForRepository(user.Login, repo.Name).Returns(prlive);
await modelService.InsertUser(new AccountCacheItem(user));
ITrackingCollection<IPullRequestModel> col = new TrackingCollection<IPullRequestModel>();
modelService.GetPullRequests(repo, col);
col.ProcessingDelay = TimeSpan.Zero;
var count = 0;
var done = new ReplaySubject<Unit>();
done.OnNext(Unit.Default);
done.Subscribe();
col.Subscribe(t =>
{
// we get all the items from the cache (items 1-5), all the items from the live (items 5-9),
// and 4 deletions (items 1-4) because the cache expired the items that were not
// a part of the live data
if (++count == 14)
{
done.OnCompleted();
}
}, () => { });
await done;
Assert.Equal(5, col.Count);
Assert.Collection(col,
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(5, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(6, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(7, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(8, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(9, t.Number); }
);
}
示例14: ignores_window_for_live_subscriptions
public void ignores_window_for_live_subscriptions()
{
ReplaySubject<int> subject =
new ReplaySubject<int>(TimeSpan.FromMilliseconds(10));
StatsObserver<int> stats = new StatsObserver<int>();
subject.Subscribe(stats);
subject.OnNext(1);
subject.OnNext(2);
subject.OnNext(3);
subject.OnCompleted();
Assert.AreEqual(3, stats.NextCount);
Assert.IsTrue(stats.NextValues.SequenceEqual(new int[] { 1, 2, 3 }));
Assert.IsTrue(stats.CompletedCalled);
}
示例15: HasObservers_OnCompleted
private static void HasObservers_OnCompleted(ReplaySubject<int> s)
{
Assert.False(s.HasObservers);
var d = s.Subscribe(_ => { });
Assert.True(s.HasObservers);
s.OnNext(42);
Assert.True(s.HasObservers);
s.OnCompleted();
Assert.False(s.HasObservers);
}