HttpRequest async

Hi !
I’m having a problem and I’d like to hear some opinions :wink:
The question is pretty simple: how to do a cocos2d::HttpRequest asynchronous?

Example:

    HttpRequest* request = new HttpRequest();
    request->setUrl(url);
    request->setRequestType(HttpRequest::Type::GET);
    request->setResponseCallback([](HttpClient* client, HttpResponse* response) {
        
        if(!response or response->getResponseCode() != 200)
        {
            return;
        }
        
        vector<char> *buffer = response->getResponseData();
        string str(buffer->begin(), buffer->end());
        // [A] : Finish Response
    });
    
    HttpClient::getInstance()->send(request);
    request->release();
    // [B] : other stuffs...

Part “B” should start running after the http response, that is, after A.
Does Cocos provide techniques to do that or I should deal with C++ functions?

I was investigating the class cocos2d::AsyncTaskPool

enum class TaskType
{
    TASK_IO,
    TASK_NETWORK,
    TASK_OTHER,
    TASK_MAX_TYPE,
};

/**
* Enqueue a asynchronous task.
*
* @param type task type is io task, network task or others, each type of task has a thread to deal with it.
* @param task: task can be lambda function to be performed off thread.
* @lua NA
*/
void enqueue(AsyncTaskPool::TaskType type, std::function<void()> task);

I’ve tried calling enqueue using TASK_NETWORK. It didn’t work.
Suggestions?

How about this simple way…

void ClassName::downloadFromInternet() {
    HttpRequest* request = new HttpRequest();
    request->setUrl(url);
    request->setRequestType(HttpRequest::Type::GET);
    request->setResponseCallback(CC_CALLBACK_2(ClassName::onDownloadComplete, this));
    HttpClient::getInstance()->send(request);
    request->release();
}

void ClassName::onDownloadComplete(HttpClient *sender, HttpResponse *response) {
    if(!response or response->getResponseCode() != 200)
    {
            return;
    }
        
    vector<char> *buffer = response->getResponseData();
    string str(buffer->begin(), buffer->end());
    // [A] : Finish Response

    // [B] : other stuffs...
}

Hey @smitpatel88 how’s it going?
Yes, I know. In fact, I’m implementing that solution.

My question was basically if there’s some solution from cocos (or c++) side for do async things through the code.

Sometimes is a better solution in order to keep the code neat.
Maybe in a game is not recommended to do async things in the main thread because it can slow the game itself, but it can be solved using other thread or something like that.

It would be useful to know if cocos provides some methods for this kind of things…