neuecc / UniRx

Reactive Extensions for Unity
MIT License
7.08k stars 891 forks source link

How to convert this to a WhenAll pattern? #523

Closed JPhilipp closed 1 year ago

JPhilipp commented 1 year ago

Great library! What's the right way to convert something like the following (this example uses a GPT-3 www request, but it could be anything)

string result1 = await textAI.GetCompletion("Albeit Einstein was");
string result2 = await textAI.GetCompletion("Susan Sarandon is");

to something that launches the GetCompletion functions simultaneously, then continues when all finished and returned their result? E.g. using pseudo-code, like this:

string result1 = null;
string result2 = null;

await Task.WhenAll({
    result1 = await textAI.GetCompletion("Albeit Einstein was"),
    result2 = await textAI.GetCompletion("Susan Sarandon is")
});

Debug.Log("Results: " + result1 + ", " + result2);

Thanks!

JPhilipp commented 1 year ago

Just realized (thanks to Evert at StackOverflow) that UniRx isn't needed in this project nowadays. The following works:

using UnityEngine;
using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
// ... snip ...

async void TestWhenAll()
{
    Task<string> a = textAI.GetCompletion("Albert Einstein was", useCache: false);
    Task<string> b = textAI.GetCompletion("Susan Sarandon is",   useCache: false);

    await Task.WhenAll(a, b);

    Debug.Log("a: " + a.Result);
    Debug.Log("b: " + b.Result);
}
elhimp commented 1 year ago

Get https://github.com/Cysharp/UniTask