将@Published 变量同时作为值和发布者发送

Sending @Published variable as both value and Publisher

有没有办法将 @Published 变量作为参数传递给需要访问变量当前值并监听值的任何更改的函数?

示例代码:

import Foundation
import Combine

class Player {
    @Published var progress = 0
}

class PlayerHandler {
    var cancellable: AnyCancellable?
    func send(progress: Int, progressPublisher: Published<Int>.Publisher) {
        print("Do something with current progress: \(progress)")

        cancellable = progressPublisher.sink {
            progr in
            print("Do something else with: \(progr)")
        }
    }
}

let handler = PlayerHandler()
let player = Player()
handler.send(progress: player.progress, progressPublisher: player.$progress)//Can I send this variable only once?
player.progress = 1
player.progress = 2

在这里,我将 progress 变量作为 IntPublished<Int>.Publisher 传递。有没有办法只传递一次变量?我该怎么做?

(我知道,我可以使用 CurrentValueSubject 而不是 @Published 变量,但我真的很喜欢能够按照 @Published 的允许直接访问 progress,而不是必须使用 progress.value)

Published.Publisher 在为其创建订阅时发出当前值。

所以你不需要手动传递当前值,你会在 Published.Publisher 上调用 sink 时得到它。

如果你想以不同的方式处理当前值和后续值的变化,你可以创建一个 Bool 标志,一旦 [=16] 发出第一个值就将其设置为 true =]并根据这个flag的值做相应的处理。

class PlayerHandler {
    var cancellable: AnyCancellable?
    private var didProcessFirstValue: Bool = false

    func send(progressPublisher: Published<Int>.Publisher) {
        cancellable = progressPublisher.sink { progr in
            if !self.didProcessFirstValue {
                print("Do something with initial progress: \(progr)")
                self.didProcessFirstValue = true
            } else {
                print("Do something else with: \(progr)")
            }
        }
    }
}