如何检测mobx的when()是否已内联完成?

时间:2019-03-07 13:24:25

标签: mobx

假设当我运行when(predicateFunction,handlerFunction)时,predicateFunction已经返回true。在这种情况下,handlerFunction在when返回之前立即运行。

是否有一种通过检查when或something的结果知道这一点的方法?还是我需要先自己调用predicateFunction()?

我问的原因是我设置了一些状态机,其中使用when建立了转换。过渡到新状态时,我不希望旧过渡运行,因此它们很清楚。问题是,如果这些过渡在我设置它们时立即运行,则在完成状态设置后它们会被清除。

我创建了这个人为的示例,第二项测试失败并显示警告。似乎想做一件很自然的事情,我想知道是否有更多mobx经验的人对如何干净地设置这种状态机有见识。

    expect(received).toBe(expected) // Object.is equality

    Expected: "AB"
    Received: "A"
import { observable, when } from "mobx";

class Observed {
    @observable
    A: boolean = false;

    @observable
    B: boolean = false;
}

class Observer {
    @observable
    state: string = "0";

    constructor(private observed: Observed) {}

    disposer: Function = () => undefined;

    setDisposer = (next: Function) => {
        this.disposer();
        this.disposer = next;
    };

    run = () => {
        this.setDisposer(
            when(
                () => this.observed.A,
                () => {
                    this.state = "A";

                    this.setDisposer(
                        when(
                            () => this.observed.B,
                            () => {
                                this.state = "AB";
                            }
                        )
                    );
                }
            )
        );
    };
}

describe("Observer", () => {
    let states: Observed;
    let observer: Observer;
    beforeEach(() => (states = new Observed()));
    beforeEach(() => (observer = new Observer(states)));

    it("waits for A then B to go into state AB", () => {
        observer.run();

        states.A = true;

        expect(observer.state).toBe("A");

        states.B = true;

        expect(observer.state).toBe("AB");
    });

    it("waits for A then B to go into state AB, but with B already set", () => {
        states.A = true;

        observer.run();

        states.B = true;

        expect(observer.state).toBe("AB");
    });
});

0 个答案:

没有答案