How to use a value from Coroutine or indicate when it will be done

For example, when calling a web API with a WWW class, I need to return a value or get feedback when this is done, and its status.

0
source share
1 answer

Well, then, let me show me a neat way to do this!

Here we make an IEnumerator that takes an action (a method in our case) as a parameter and calls it when our WWW is executed:

    public static IEnumerator GetSomething(Action<string> callback)
    {
        // The www-stuff isn't really important to what I wish to mediate
        WWWForm wwwForm = new WWWForm();
        wwwForm.AddField("select", "something");
        WWW www = new WWW(URL, wwwForm);
        yield return www;

        if (www.error == null)
        {
            callback(www.text);
        }
        else
        {
            callback("Error");
        }
    }

And here is how we use it:

StartCoroutine(
    GetSomething((text) => 
    {
        if (text != "Error")
        {
            // Do something with the text you got from the WWW
        }
        else
        {
            // Handle the error
        }
    })
);

, , (text), . " " IEnumerator, -, , , , GetSomething.

+1

Source: https://habr.com/ru/post/1667884/


All Articles