/// <summary> /// 异步操作的Subject /// </summary> public static void AsyncSubjectConvertTask() { //var tcs = new TaskCompletionSource<bool>(); //var task = tcs.Task; var sbj = new AsyncSubject <string>(); sbj.SubscribeConsole(); var task = PrimeGenerator.GenerateAsync(5); task.ContinueWith(t => { switch (t.Status) { case TaskStatus.RanToCompletion: sbj.OnNext(string.Join(",", t.Result)); sbj.OnCompleted(); break; case TaskStatus.Canceled: sbj.OnError(t.Exception.InnerException); break; case TaskStatus.Faulted: sbj.OnError(new TaskCanceledException(t)); break; } }, TaskContinuationOptions.ExecuteSynchronously); //tcs.SetResult(true); }
/// <summary> /// 一个典型的错误使用 Subject 的方式,就是用来合并两个 Observable,合并应该用 Merge /// 使用 Subject 前先思考一下,有没有重新造轮子了 /// </summary> public static void ClassicMisuse() { var sbj = new Subject <string>(); sbj.SubscribeConsole(); Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)).Select(x => $"IEnumerable {x}").Subscribe(sbj); // 这个 Observable 没有机会完成,因为另一个 Observable 先完成了,所以整个Subject 就完成了 PrimeGenerator.GenerateAsync(5).ToObservable().SelectMany(x => x.Select(y => $"Task {y}")).Subscribe(sbj); }