return IEnumerator

I am using a structure like this.

I want to return true when it is done, but I couldn’t, can you please help?

Main Script

Other Script


IEnumerator:

You can’t return things that way from a coroutine.

Instead pass in a delegate (also known as a callback function) and have the coroutine call it when it’s complete.

You can pass a single delegate, or you can pass in two delegates, one for success and one for failure.

1 Like

Thank you for your answer
How can I connect to other script? I do not understand the delegate structure. (if true else false …)

C# has a few built-in delegates you can use for common cases, so there’s not really a need to create your own delegate for this. You can use the built-in Action delegate, which is just a typical callback you can invoke.
There are generic versions of the Action delegate as well that allow you to pass parameters in the callback.

The idea behind a callback structure is that, instead of waiting for a return value from a method, the method invokes other methods to signal when some process is done. If you’re familiar with JavaScript Promises, the concept is very similar.

For your case, you probably want a callback structure like this for your GetRefreshToken method:

//This onComplete Action takes in a bool parameter that must be passed in when invoked.
IEnumerator GetRefreshToken(Action<bool> onComplete) {
   bool isSuccess = /* Your refresh logic */

   //Invoke the Action to complete the callback, passing in the value of whether or not the refresh was successful.
   onComplete.Invoke(isSuccess);
}

As for passing in a callback as a parameter, you can do it in two different ways:

Create another method to handle the callback:

void Refresh() {
   //The GetRefreshToken method will call OnRefreshComplete when finished.
   StartCoroutine(GetRefreshToken(OnRefreshComplete));
}

void OnRefreshComplete(bool isSuccess) {
   if(isSuccess) {
      //Success logic.
   }
   else {
     //Error logic.
   }
}

Or create an inline lambda expression to handle the callback. Lambda expressions follow this syntax:
(input-parameters) => { method-execution }

void Refresh() {
   //The GetRefreshToken method will call the lambda expression when finished.
   StartCoroutine(GetRefreshToken((bool isSuccess) => {
      if(isSuccess) {
         //Success logic.
      }
      else {
        //Error logic.
      }
   }));
}
2 Likes

Thank you very much, you solved my problem. :slight_smile: