CombineとAsyncStreamでの処理を比較してみる(2)
Combine処理をAsyncStream処理への置換したコード事例を見てみる
// 入力値の受け皿となる変数
let email = PassthroughSubject()
let userID = PassthroughSubject()
// 入力値を元にボタンの活性・非活性を決定する
let cancellables = email.removeDuplicates()
.combineLatest(userID.removeDuplicates())
.map { email, userID in
!email.isEmpty && !userID.isEmpty
}
.sink(
receiveCompletion: { _ in },
receiveValue: { [weak self] shouldActivate in
// ボタンの状態を更新する処理
self?.handleUpdateButton(shouldActivate: shouldActivate)
}
)
// データを入力する
email.send("
[email protected]")
userID.send("sampleNumber123")
cancellables.cancel()
// 入力値の受け皿となる変数
let email = AsyncChannel()
let userID = AsyncChannel()
// 入力値を元にボタンの活性・非活性を決定する
let stream = combineLatest(email.removeDuplicates(), userID.removeDuplicates())
.map { email, userID in
!email.isEmpty && !userID.isEmpty
}
// データを入力する
Task {
await email.send("
[email protected]")
await userID.send("sampleNumber123")
email.finish()
userID.finish()
}
// ボタンの状態を更新する処理
for try await shouldActivate in stream {
handleUpdateButton(shouldActivate: shouldActivate)
}
両方の入力状態を監視する
入力の受け皿となる変数
※この処理例はかなり類似した事例