WWDC2019 Combine in Practice

2019-07-18  本文已影响0人  Jerrydu96

简单的将Publisher的输出编码为JSON

.decode(MagicTrick.self, JSONDecoder())

Failure Handling Operators

assertNoFailure
retry
catch
mapError
setFailureType

可以通过以下代码来在失败的时候来替换一个Publisher

.flatMap { data in
    return Just(data)
        .decode(MagicTrick.self, JSONDecoder())
        .catch {
            return Just(MagicTrick.placeholder)//返回一个默认值继续
         }
}
.publisher(for: \.name)//新的Publisher

Scheduled Operators

delay//延迟
debounce//不超过
throttle
receive(on:)//放到别的地方
subscribe(on:)

Scheduler describers
·When
·Where
Supported by RunLoop andDispatchQueue

取消任务 Cancellation

// Using Subscribers with Combine
let trickNamePublisher = ...
let canceller = trickNamePublisher.assign(to: \.someProperty, on: someObject)

//...
canceller.cancel()

Built into Combine
Terminate subscriptions early

自动执行cancel在deinit的时候
protocol Cancellable {
    func cancel()
}
final class AnyCancellable: Cancellable {} //Calls 'cancel' on deinit

Subjects

Behave like both Publisher and Subscriber
Broadcast values to multiple subscribers

protocol Subject: Publisher, AnyObject {
    func send(_ value: Output)
    func send(completion: Subscribers.Completion<Failure>)
}
// Using Subjects with Combine
let trickNamePublisher = ... // Publisher of <String, Never>

let magicWordsSubject = PassthroughSubject<String, Never>()

trickNamePublisher.subscribe(magicWordsSubject)

let canceller = magicWordsSubject.sink { value in
    // do something with the value
}

magicWordsSubject.send("Please")

let sharedTrickNamePublisher = trickNamePublisher.share()

Working with SwiftUI

SwiftUI owns the Subscriber
You just need to bring a Publisher

SwiftUI BindableObject
//这就是SwiftUI可以实时更新的原理之一
protocol BindableObject {
    associatedtype PublisherType : Publisher where PublisherType.Failure == Never
    var didChange: PublisherType { get } 
}
// you can see more things in
Data Flow in SwiftUI WWDC 2019
// Combine with SwiftUI
class WizardModel : BindableObject {
    var trick: WizardTrick { didSet { didChange.send() }
    var wand: Wand? { didSet { didChange.send() }

    let didChange = PassthroughSubject<Void, Never>()
}

@Published

Property wrapper
Adds a publisher to any property

//Using @Published
@Published var password: String = ""

self.password = "1234"

let currentPassword: String = self.password

let printerSubscription = $password.sink {
    print("The published value is '\($0)'") // now is "password"
}

self.password = "password" 

Debounce

Use Combine Today

Compose small parts into custom publishers
Adopt incrementally
Add a Publisher to a property with @Published
Compose callbacks and Publishers with Future

上一篇下一篇

猜你喜欢

热点阅读