我如何从timer.publish属性中传递两个参数给Swift/合并方法

gblwokeq  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(108)

我有一个计时器方法,每当创建新示例时都会调用它。我希望每个股票代码都应该存储在字典中,关于每个示例,如**[test1:1,test2:1],[test1:2,test2:2] ...**...等等。已尝试以下选项,但无法发送任何值。目前.scan只能发送整数

var subscriptions = Set()
var dict = NSMutableDictionary()

func multiplecall(name: String) {
Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
.scan(1) { value, _ in value + 1 }
.sink(receiveValue: fetchValues)
.store(in: &subscriptions)
}

func fetchValues(ticker: Int){
print(ticker)

}


**Expecting something like this**
    func fetchValues(testName: String, ticker: Int){
    dict[testName] = ticker
    }

multiplecall(name: "test1")
multiplecall(name: "test2")
ozxc1zmp

ozxc1zmp1#

你不需要在这里做任何特别的事情。不要将fetchValues传递给sink,而是传递一个闭包:

.sink(receiveValue: { value in
    fetchValues(testName: name, ticker: value)
})

或者简单地说:

.sink { value in
    fetchValues(testName: name, ticker: value)
}

下面是一个完整的代码,它在发布前5个值后打印字典:

var subscriptions = Set<AnyCancellable>()
var dict = [String: Int]()

func multiplecall(name: String) {
Timer.publish(every: 1, on: .main, in: .common)
    .autoconnect()
    .scan(1) { value, _ in value + 1 }
    .prefix(5)
    .sink { _ in
        print(dict)
    } receiveValue: { value in
        fetchValues(testName: name, ticker: value)
    }
    .store(in: &subscriptions)
}

func fetchValues(testName: String, ticker: Int){
    dict[testName] = ticker
}

multiplecall(name: "test1")
multiplecall(name: "test2")

输出:

["test1": 6, "test2": 5]
["test1": 6, "test2": 6]

请注意,第一行是从第一个发布者完成时生成的。此时test2尚未完成。这就是为什么它是"test2": 5

相关问题