Home > Net >  Best way to make a function wait / block and then signal that function to continue from another func
Best way to make a function wait / block and then signal that function to continue from another func

Time:09-17

I am busy building an app that uses MQTT as a communication channel. The data comes in on a stream in an async manner. So I want to use the MQTT in a 2-way communication manner. I am starting off by building the login dialog for a user. So what will happen is that the app will build the login dialog that has the username and password on, when the user clicks on login the app will send a command on a topic that the server is listening on and the the app needs to wait and not remove the login dialog and show a spinner to the user to show that the app is waiting. The app will receive its answer on another topic it is listening on that the server will send the result on.

So my question is this. What is the best way to have the login dialog block / wait until we get a message on the topic that the server will send. This data will come in a stream that is not part of the login call. I do have access to the data via Provider. And how do I then send a message to the blocking dialog to continue. All the example I see is with await on the call to an API. The API will return on the same call. In my case the API will not return as it is running async. I also want an timeout on the blocking / waiting login dialog should we not get a response from the server.

So I need to wait (how do I wait? Do I sit in a while loop with sleeps? Is there a better way?) until I get the data back on a topic and then continue on getting the data or a timeout. I do have the MQTT all working, just need to figure out the best way to wait / block and then pass the data to that wait / blocking function to tell it to continue.

CodePudding user response:

So I have it working like this. Not sure if there is a better way but this works 100%

        //Update the result
        appState.loginResult = 'X';
        timeoutCounter = 0;

        //We sit in the loop until the data changes from X
        while (appState.loginResult == 'X') {
          await Future.delayed(Duration(milliseconds: 200));
          timeoutCounter  ;
          if (timeoutCounter >= 25) {
            appState.loginResult = 'T';
          }

CodePudding user response:

You can store a reference to the dialog inside your activity/fragment. You can keep it up just dont close it? Then whatever logic you have you can simply call the dialog in a way or another (via a callback or interface).

  • Related