Stream Chat Unreal SDK
Loading...
Searching...
No Matches
CallbackAction.h
1// Copyright 2022 Stream.IO, Inc. All Rights Reserved.
2#pragma once
3
4#include "CoreMinimal.h"
5#include "Engine/Engine.h"
6#include "Engine/LatentActionManager.h"
7#include "LatentActions.h"
8#include "UObject/WeakObjectPtr.h"
9
10template <class T, class Arg = const T&>
11class TCallbackAction final : public FPendingLatentAction
12{
13public:
14 TCallbackAction(T& Result, const FLatentActionInfo& LatentInfo)
15 : ExecutionFunction(LatentInfo.ExecutionFunction), OutputLink(LatentInfo.Linkage), CallbackTarget(LatentInfo.CallbackTarget), Result(Result)
16 {
17 }
18 TCallbackAction(const TCallbackAction&) = delete;
19 TCallbackAction& operator=(const TCallbackAction&) = delete;
20
21 static void CreateLatentAction(
22 const UObject* WorldContextObject,
23 const FLatentActionInfo LatentInfo,
24 T& Output,
25 TFunctionRef<void(TFunction<void(Arg)> Callback)> Action)
26 {
27 if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
28 {
29 FLatentActionManager& LatentActionManager = World->GetLatentActionManager();
30 if (LatentActionManager.FindExistingAction<TCallbackAction<T, Arg>>(LatentInfo.CallbackTarget, LatentInfo.UUID))
31 {
32 return;
33 }
34
35 TCallbackAction<T, Arg>* DelegateAction = new TCallbackAction(Output, LatentInfo);
36 Action(
37 [DelegateAction](Arg InResult)
38 {
39 DelegateAction->Result = InResult;
40 DelegateAction->bDone = true;
41 });
42 LatentActionManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, DelegateAction);
43 }
44 }
45
46private:
47 virtual void UpdateOperation(FLatentResponse& Response) override
48 {
49 Response.FinishAndTriggerIf(bDone, ExecutionFunction, OutputLink, CallbackTarget);
50 }
51
52 FName ExecutionFunction;
53 int32 OutputLink;
54 FWeakObjectPtr CallbackTarget;
55 T& Result;
56 bool bDone = false;
57};