Search code examples
iosasynchronousdelegatessocketrocket

Socket Rocket Asynchronous delegate methods


Using Socket Rocket library for WebSocket connections.

When I saw the source of Socket Rocket, it is clearly visible that it is calling the methods of its delegate class (my class) asynchronously using dispatch_async.

But when in my class where the delegate the method is implemented, I put a infinite while loop, the UI gets blocked.

Why is that so when the delegate method is already called asynchronously?

SRWebsocket.m

- (void)_handleMessage:(id)message
{
SRFastLog(@"Received message");
[self _performDelegateBlock:^{
    [self.delegate webSocket:self didReceiveMessage:message];
}];
}

// Calls block on delegate queue
- (void)_performDelegateBlock:(dispatch_block_t)block;
{
if (_delegateOperationQueue) {
    [_delegateOperationQueue addOperationWithBlock:block];
} else {
    assert(_delegateDispatchQueue);
    dispatch_async(_delegateDispatchQueue, block);
}
}

My delegate implementation (code that should have been handled asynchronously)

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {

//some code to process message

//emulating a long running operation
while(1)
{
}


}

But when I put a dispatch_async in my long running operation, the UI doesnt get blocked.

Is it because the block as a whole is run asynchronously but the delegate call inside it is done synchronously. So, as soon as the delegate call is over, _performDelegateBlock returns?

Please explain


Solution

  • _delegateDispatchQueue - default value will your main queue. So, if you want to run code asynchronously for your delegate, you need to provide your own queue