ReactKit / SwiftState

Elegant state machine for Swift.
MIT License
903 stars 93 forks source link

Machine.addHandler(transition: order: handler:) -> Disposable not working ? #39

Closed toshi0383 closed 8 years ago

toshi0383 commented 8 years ago

I modified the basic test case as following and it's failing. Any ideas to get rid of ?

    func testREADME_tryEvent()
    {
        var handlerCalled = false
        let machine = StateMachine<MyState, MyEvent>(state: .State0) { machine in

            // add 0 => 1 => 2
            machine.addRoutes(event: .Event0, transitions: [
                .State0 => .State1,
                .State1 => .State2,
            ])
            machine.addHandler(.Any => .Any) { _ in
                handlerCalled = true
            }
        }

        // initial
        XCTAssertEqual(machine.state, MyState.State0)

        // tryEvent
        machine <-! .Event0
        XCTAssertEqual(machine.state, MyState.State1)

        // tryEvent
        machine <-! .Event0
        XCTAssertEqual(machine.state, MyState.State2)

        // tryEvent (fails)
        machine <-! .Event0
        XCTAssertEqual(machine.state, MyState.State2, "Event0 doesn't have 2 => Any")

        XCTAssertTrue(handlerCalled) // Failure
    }
inamiy commented 8 years ago

In your example, you are registering event-based routes but attaching state-based handler, so it doesn't react to any event-triggering.

To fix this, please replace:

// register handler for state-based transition, e.g. `machine <- .State0`
machine.addHandler(.Any => .Any) { ... }

to:

// register handler for event-based transition, e.g. `machine <-! .Event0`
machine.addHandler(event: .Event0) { ... }
toshi0383 commented 8 years ago

I thought it was working in previous version, though ?

inamiy commented 8 years ago

Yes, previous ver 3.x was working in that way (equal to addEventHandler()). From ver 4.0.0, you need to use machine.addHandler(event:) instead.

P.S. For reacting to any events, you can use machine.addHandler(event: .Any).

inamiy commented 8 years ago

Updated README.md in 84d4b42511c06f5fed95aeb5644b5f23d447c204.

toshi0383 commented 8 years ago

👏 I see that. Thanks !

philipbel commented 3 years ago

Hello.

I find this behavior surprising. I was just playing with SwiftState, and wanted to model the state machine using a mix of events and states. The idea being that I would attach handlers to the states, but send events to the machine to transition.

I understand this is not possible—I would have to choose events or states, but not both.