landelare / ue5coro

A C++20 coroutine implementation for Unreal Engine 5 that feels almost native.
BSD 3-Clause Clear License
543 stars 48 forks source link

Return values from coroutines #7

Closed broly closed 1 year ago

broly commented 1 year ago

Sometimes, when I awaited some data, for example of async loading of resources. I need return it from my coroutine. The best thing that comes to mind is using TTask with co_return. Can you add support for this?

For example:

UE::Tasks::TTask<UItemInstance*> GrantItem(TSoftObjectPtr<UItemAsset> ItemAssetSoft)
{
    UItemAsset* ItemAsset = co_await UE5Coro::Latent::AsyncLoadObject(ItemAssetSoft);

    UItemInstance* ItemInstance = CreateItemInstance(ItemAsset);

    co_return ItemInstance;
}

But TTask is not awaitable? Maybe add new type of task, like TCoroTask?

landelare commented 1 year ago

In 1.6 the next best thing you can do is FAsyncCoroutine GrantItem(TSoftObjectPtr<T> X, UItemInstance*& Y); with a suitably long-lived pointer. This has the added benefit of being compatible with UFUNCTION.

I'm not willing to mark an engine type as a coroutine, that would break a lot of things. I have experimented with a TAsyncCoroutine<T> subclass that has return values. It's not straightforward to do, which is why it hasn't shipped. :) It's on the list of things I'm interested in adding, but no timeline as to when/if it will happen.

broly commented 1 year ago

Ok, I just want to say: it's would be very useful stuff, especailly with TTuple.

Also I think we can always make USTRUCT child from templated TAsyncCoroutine. And it seems lot of code with coroutines should use UFUNCTIONs rarely.

(I wish templated objects will be supported by UHT. They made possibility to add custom plugins, will see...)

landelare commented 1 year ago

1.7 will add support for co_return value;