class ProfileViewReactor: Reactor {
// 代表用户行为
enum Action {
case refreshFollowingStatus(Int)
case follow(Int)
}
// 代表附加作用
enum Mutation {
case setFollowing(Bool)
}
// 代表页面状态
struct State {
var isFollowing: Bool = false
}
let initialState: State = State()
}
func mutate(action: Action) -> Observable<Mutation> {
switch action {
case let .refreshFollowingStatus(userID): // receive an action
return UserAPI.isFollowing(userID) // create an API stream
.map { (isFollowing: Bool) -> Mutation in
return Mutation.setFollowing(isFollowing) // convert to Mutation stream
}
case let .follow(userID):
return UserAPI.follow()
.map { _ -> Mutation in
return Mutation.setFollowing(true)
}
}
}
reduce()
reduce() 通过旧的 State 以及 Mutation 创建一个新的 State。
func reduce(state: State, mutation: Mutation) -> State
这个方法是一个纯函数。它将同步的返回一个 State。不会产生其他的作用。
func reduce(state: State, mutation: Mutation) -> State {
var state = state // create a copy of the old state
switch mutation {
case let .setFollowing(isFollowing):
state.isFollowing = isFollowing // manipulate the state, creating a new state
return state // return the new state
}
}