funcmutate(action: Action) -> Observable<Mutation> {switch action {caselet .refreshFollowingStatus(userID):// receive an actionreturn UserAPI.isFollowing(userID)// create an API stream .map { (isFollowing:Bool) -> Mutation inreturn Mutation.setFollowing(isFollowing)// convert to Mutation stream }caselet .follow(userID):return UserAPI.follow() .map { _-> Mutation inreturn Mutation.setFollowing(true) } }}
reduce()
reduce() 通过旧的 State 以及 Mutation 创建一个新的 State。
funcreduce(state: State, mutation: Mutation) -> State
这个方法是一个纯函数。它将同步的返回一个 State。不会产生其他的作用。
funcreduce(state: State, mutation: Mutation) -> State {var state = state // create a copy of the old stateswitch mutation {caselet .setFollowing(isFollowing): state.isFollowing = isFollowing // manipulate the state, creating a new statereturn state // return the new state }}