Multiple threads calling same function Swift/SwiftUI

187 Views Asked by At

I have scenario where threads calling the same method which is having timer, for each thread timer will be different because thread created in different timeline based on the action from the UI. How can I get the timer value for each thread separately in single view and single init of the class, though I tried to get the different response but for dynamic creation of threads its not responsive, below one I am just trying on playground

var groupqueue = DispatchGroup()
private var update: [AnyCancellable] = []
var ticker: Int = 0

groupqueue.enter()
multiplecall(name: "test1")

groupqueue.enter()
multiplecall(name: "test2")

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

}

func fetchValues(){
        ticker += 1
        print(ticker)
    }

required output : 1 1, 2 2, 3 3...\n

what I am getting: 1,2,3,4...

1

There are 1 best solutions below

3
Scott Thompson On

Your code sample is incomplete. Some of the variables aren't declared, and it's not clear why you are trying to use a dispatch group, the name you pass to multicall is not used. There are a number of problems.

I copied your code into a Playground and edited it as follows:

import UIKit
import Combine

var subscriptions = Set<AnyCancellable>()

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)
}

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

This produces the output you say you are expecting.

I note that this code does not appear to be multithreaded. The timer is set to publish on the main thread so all of the code in this sample will be run on the main thread. The timers themselves might be running on separate threads (I haven't ever looked to see how Timer is implemented) but the timer events are delivered to the main run loop.