Important: Please read the Qt Code of Conduct -

Deferring signals

  • I'm doing a similar design (actually an abstraction above QNetwork classes) as the QNetwork module for accessing resources. I have a repository class with request methods and each method returns a reply object associated with the specific request.

    When using my abstraction with the QNetwork implementation everything works fine, I get a reply object (wrapping a QNetworkReply) which I can use to connect to signals and the slots will be invoked when the job is done.

    My problem is that I also need a mock implementation of the abstraction but this fails because I emit the signals directly when I do the request, before the reply object is returned and this is of course the expected behavior.

    How is the signaling deferred in QNetworkReply? You don't connect to the signals on the reply object until after the request is already executed, or am I wrong here? Is there more magic behind this?

    I suppose it would be possible to use timers and defer the signaling but it sounds more complicated that necessary.

  • Not looked deep into QtNetwork, but as quick answer can propose to create signals queue and keep signals there while nobody connected to signal. If somebody connected to signal than emit all queue.

  • Signals are not deferred in QNetworkReply. The signals are just not emitted after control returns to the event loop and network events are processed.

    For your mock, use of a timer seems appropriate and not overly complicated.

  • Thanks guys!

    I suspected that the network stuff had some kind of processing in the event loop to accomplish what I want.

    I did a prototype with Denis's suggestion. QObject has a protected method, "connectNotify": (which will be called when someone connects to a signal), which I can override and emit the signal if no connections has been made to the signal before. The prototype seems to work well.

    This should also be safe to use from thread I believe?!

    @bradley You're right, the timer is not overly complicated for my mock but I wanted a more solid solution in case I need to do something similar in the future :) The timer will only solve the problem if you add a slot before the timer expires which you can't guarantee, or have an expiration time of >5 seconds.

Log in to reply