Ganesh
Ganesh

Reputation: 89

Stop Dispatchqueue using NotificationCenter in swift 3

I have some task which I want to do asynchronously. So I am creating dispatchqueue in one class and doing some task.

//Adding Observer      
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification).

.

//Creating Background Thread.
     let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)

    //Asynch thread.
    anotherQueue.async {
        for i in 0..<50 {
       print("\n 🔴",i)
            sleep(1)
        }
    }

but upon some events I want to stop this, and am handling something like this.

func catchNotification (notification:Notification) -> Void {
    //Stop the queue.
    anotherQueue.suspend()
}

Am posting notification some other class. notification is getting received. but thread is not getting suspended.

Here is the complete class if you want to refer.

LoginPresenter.swift

let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)
class LoginPresenter : LoginInteractor {
func catchNotification (notification:Notification) -> Void {
    //Stop the queue.
    anotherQueue.suspend()
}

func LoginSuccessFull()
{   
    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification)

    //Asynch thread.
    anotherQueue.async {
        //Synch
        for i in 0..<50 {
       print("\n 🔴",i)
            sleep(1)
        }
    }
}

or is any other better method or mechanism is there to do this ?

Upvotes: 1

Views: 2041

Answers (1)

dirtydanee
dirtydanee

Reputation: 6151

Reading Apple`s GCD documentation, you could see the following:

The suspension occurs after completion of any blocks running at the time of the call.

This means that, every block will be executed, what has already been started. Just create a second block in your LoginSuccessFull function like:

anotherQueue.async {
  print("this is the second block")
}

If you suspend straight after the function call, this block will not be executed.

If you would like to cancel immediately the operations in GCD, you will have to write you own implementation. But to how, it is always the one question for GCD, because it is just not designed that way.

The other option would be to use NSOperationQueue, but there you have implement right the cancel logic for your NSOperation subclasses.

Upvotes: 1

Related Questions