强制lambda重新评估作为Rx序列的一部分

时间:2015-04-28 14:10:06

标签: c# lambda system.reactive

我正在尝试生成进度消息并通过IObservable发布。

Func<JobProgressMessage> nextMsg = () => ProgressManager.InProgressMessage("progressing");

var o = Observable
    .Return(nextMsg())
    .Repeat()
    .Timeout(TimeSpan.FromSeconds(2))
    .Retry(100)
    .Finally(() =>
        job.AddMessage<ProgressCompleted>(ProgressManager.CompletedMessage("Completed")));

我发现nextMsg()仅在同一条消息发布后进行评估。我希望Repeat每次都会导致lambda重新评估。

2 个答案:

答案 0 :(得分:1)

每当您订阅observable时需要重新评估某些内容(包括Defer重复订阅),Func<JobProgressMessage> nextMsg = () => ProgressManager.InProgressMessage("progressing"); var o = Observable .Defer(() => Observable .Return(nextMsg())) .Repeat() .Timeout(TimeSpan.FromSeconds(2)) .Retry(100) .Finally(() => job.AddMessage<ProgressCompleted>ProgressManager.CompletedMessage("Completed"))); 就是您想要的:

Defer

基本上,在订阅时,nextMsg会评估传入的函数,以便在每个订阅上获得新的observable。然后,当然UPDATE TAB_EXAM_FORMS SET RNO_CODE = CAST(RAND(CHECKSUM(NEWID())) * 10 AS INT) + 1 也将被重新评估。

答案 1 :(得分:0)

根据nhabuiduc的建议,最简单的方法是

var o = Observable.Return(ProgressManager.InProgressMessage("progressing"))
                          .Repeat()
                          .Timeout(TimeSpan.FromSeconds(2))
                          .Retry(100)
                          .Finally(() => job.AddMessage<ProgressCompleted>(ProgressManager.CompletedMessage("Completed")));

var s = o.Subscribe(m => job.AddMessage(ProgressManager.InProgressMessage("progressing")));

但最后,我想玩Observables,我最终得到了

var s = Observable.Defer(()=>Observable.Return(nextMsg()))
                  .Delay(TimeSpan.FromSeconds(2))
                  .Repeat(100)
                  .Finally(() => job.AddMessage<ProgressCompleted>(ProgressManager.CompletedMessage("Completed")))
                  .SubscribeOn(Scheduler.ThreadPool)
                  .Subscribe(m => job.AddMessage(m));