为什么没有 Observable.Finally 被调用?

编程入门 行业动态 更新时间:2024-10-28 18:34:32
本文介绍了为什么没有 Observable.Finally 被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我不理解Finally 方法.在这种情况下它不会触发.

I'm not understanding the Finally method. It doesn't fire in this situation.

[TestMethod]
public void FinallyHappensOnError()
{
    bool finallyActionHappened = false;
    try
    {
        Observable
        .Throw<Unit>(new DivideByZeroException())
        .Finally(() => finallyActionHappened = true)
        .Subscribe();
    }
    catch
    {
    }
    Assert.IsTrue(finallyActionHappened);
}

这个使用 Do 而不是 finally 来工作.我不明白为什么它适用于 Do 而不是最终.

This one works using Do rather than Finally. I don't understand why it works with Do but not Finally.

[TestMethod]
public void CanRecordWhenSequenceFinishes()
{
    bool sequenceFinished = false;
    try
    {
        Observable.Throw<Unit>(new DivideByZeroException())
        .Do(
            onError: ex => { sequenceFinished = true; },
            onCompleted: () => sequenceFinished = true,
            onNext: _ => { })
        .Subscribe();
    }
    catch
    {

    }
    Assert.IsTrue(sequenceFinished);
}

推荐答案

你的代码(双向)是一个竞争条件.竞争条件用 .Do 解决正确的方法,用 .Finally 解决错误的方法.为什么比如何避免它更不重要:

Your code (both ways) is a race condition. The race condition resolves the right way with .Do and the wrong way with .Finally. Why is less relevant than how to avoid it:

public async Task FinallyHappensOnError()
{
    bool finallyActionHappened = false;
    try
    {
        await Observable.Throw<Unit>(new DivideByZeroException())
            .Finally(() => finallyActionHappened = true);
    }
    catch
    {
    }
    Assert.IsTrue(finallyActionHappened);

}

或者,如果您不想使用 TPL/async/await:

or, if you don't want to use TPL/async/await:

[TestMethod]
public void FinallyHappensOnError()
{
    bool finallyActionHappened = false;
    try
    {
        Observable
        .Throw<Unit>(new DivideByZeroException())
        .Finally(() => finallyActionHappened = true)
        .Subscribe(
            _ => {},
            () => Assert.IsTrue(finallyActionHappened)
        );
    }
    catch
    {
    }

}

这篇关于为什么没有 Observable.Finally 被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 12:24:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1409307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Observable   Finally

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!