Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to relay the response of a asynchronous request



  • I'm new to Qt and I am not able to find a way to the following scenario where I am using asynchronous calls.

    void main()
    {
        ClassA objA;
        bool bResponse = objA.MakeRequest();
        .
        .
        .
        //Some other stuff 
    }
    
    //SIGNAL:
    bool ClassA::MakeRequest()
    {
        emit Request;
        //<-Server Response should come here
    }
    
    //Corresponding SLOT:
    void ClassB::OnRequest()
    {
        QUrl url(Some_Path);
        QNetworkRequest qRequest(url);
        qNetworkAccessManagerObj->post(qRequest, QByteArray());
    
    }
    
    //Following slot invoked when QNetworkAccessManger::finished(QNetworkReply*) signal is emitted
    
    void ClassB::OnServerResponseRecieved(QNetworkReply* qReply)
    {
        threadObj->serverResponse = qReply->readAll();
    }
    
    void ThreadClass::run()
    {
        bool bResponse;
        if (serverResponse == 500) //500 is Server Response Success Code
        {
            bResponse = true;
        }
        else
        {
            bResponse = false;
        }
    }
    

    I need to get back the response from EmitRequest(), Only on getting the response I need to continue executing other lines of code in the main().

    The question is that is it possible to relay the bResponse back to where I was emitting the request() SIGNAL so I can return the value? If not, Is there a workaround?



  • Make ClassB emit a signal with the reply connected to ClassA


    I'm new to Qt

    ThreadClass

    This is a dangerous combo



  • @VRonin But I want the server response to where Im emitting the signal. So that I can return it as part of the EmitRequest()


  • Lifetime Qt Champion

    @Abhi_Varma Why should a method called EmitRequest() return the response?! The method name says: it emits the request, it does not say it returns the response. If you want synchronous API (for what ever reason) then at least name the method differently. Why do you want blocking behaviour? It will block your UI.



  • @VRonin said in How to relay the response of a asynchronous request:

    Make ClassB emit a signal with the reply connected to ClassA


    I'm new to Qt

    ThreadClass

    This is a dangerous combo

    LMAO :-)
    but true.


Log in to reply