Now I want to notify value change from delegate event to another func() and returns the new value with callback(). To do that, I tried to write test program as below. However, problem happened.
import SwiftUI
struct ContentView: View {
let cst = CombineSinkTest()
var body: some View {
Button(action: {
cst.sinkTest(stCount: 0){ sinkResult in
print("finish")
}
}){
Text("Push")
}
}
}
import Foundation
import Combine
final public class CombineSinkTest: NSObject{
var stringPublisher = PassthroughSubject<String?, Never>()
var cancellables = [AnyCancellable]()
private var globalNum = 0
var sinkDefinedFlag = false
func sinkTest(stCount: Int, completion: @escaping (Bool) -> Void){
var localCount = stCount
childSink(count: localCount){ childResult in
localCount += 1
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
self.sinkTest(stCount: localCount){ stResult in
completion(true)
}
}
}
}
func childSink(count: Int, completion: @escaping (Bool) -> Void ){
globalNum += 1
let localNum = globalNum
print("globalNum: \(localNum)")
if(sinkDefinedFlag == false) {
self.stringPublisher
.sink(receiveCompletion: { print ("completion: \($0)") },
receiveValue: {
print ("received: \($0)")
print("local value: \(localNum)")
completion(true)
})
.store(in: &cancellables)
sinkDefinedFlag = true
}
(a) generateNotification()
}
(a) private func generateNotification() {
stringPublisher.send("")
}
}
(a) is test-purpose. (a)'s func is planned to be delegate event.
I want to let receiveValue: in .sink to use localCount number. However, localCount won't increase at all...
globalNum: 1
localNum in caller of .sink: 1
received: Optional("")
localNum in .sink: 1
globalNum: 2
localNum in caller of .sink: 2
received: Optional("")
localNum in .sink: 1
globalNum: 3
localNum in caller of .sink: 3
received: Optional("")
localNum in .sink: 1
globalNumber is increasing. And, localNum in func defining .sink. However, localCount in .sink closure won't increase. How should I change the code for passing updated localNum into .sink closure?
Sorry for not good English... Best regards,