目录
目录README.md

TrackedValue

Build Status codecov cocoapods

TrackedValue is a struct that determines whether a value has changed or not.

Original Idea: ReactorKit#74

Example

var v1 = TrackedValue(1)
let v2 = v1
v1 == v2 // true

v1.value = 1 // same value but new one assigned
v1 == v2 // false

Use case

final class LoginReactor: Reactor {
    enum Action {
        case login
    }

    struct State {
        var error: Error?
    }

    let initialState = State()
}

final class LoginViewController: UIViewController, View {
    func bind(reactor: LoginReactor) {
        reactor.state.map { $0.error }
            // For some reasons, we need to skip if the error is same instance.
            // We can not use `distinctUntilChanged` here. 😭
            // Becase `Error` protocol is not `Equatable`.
            .distinctUntilChanged()
            .bind { [weak self] in self?.showError($0) }
            .disposed(by: disposeBag)
    }
}

If we use the TrackedValue, we can determine a value is changed or not. Even if the original value is not Equatable.

final class LoginReactor: Reactor {
    enum Action {
        case login
    }

    struct State {
        var error: TrackedValue<Error?> = .init(nil)
    }

    let initialState = State()
}

final class LoginViewController: UIViewController, View {
    func bind(reactor: LoginReactor) {
        reactor.state.map { $0.error }
            // We can use `distinctUntilChanged`! 😀
            .distinctUntilChanged()
            .bind { [weak self] in self?.showError($0.value) }
            .disposed(by: disposeBag)
    }
}
关于
49.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

©Copyright 2023 CCF 开源发展委员会
Powered by Trustie& IntelliDE 京ICP备13000930号