- Home /
How to pass data to callback through coroutine
I have a beginner question. I run a coroutine during some authentication code that fetches additional data from a server, after which I want to continue on with the additional data. Right now I do this:
private AuthRequestMessage _authRequestMessage;
private NetworkConnection _conn;
public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
{
_authRequestMessage = msg;
_conn = conn;
StartCoroutine(API.GetOTPForUser(msg.user, ReceiveOTPForUser));
}
// Called when we receive the OTP from the API for the user trying to log in.
private void ReceiveOTPForUser(OTP userOTP)
{
var msg = _authRequestMessage;
var conn = _conn;
... code continues
}
You can see I'm saving some state as private variables. I know I could pass these both into the coroutine and receive them back in the callback, but that involves changing the coroutine itself to pass along the all that data, which has little to do with what the coroutine actually does. Is there a better way to get this data from the function starting the coroutine to the callback? How would you handle this?
Answer by Hellium · Oct 13, 2021 at 08:30 PM
// private AuthRequestMessage _authRequestMessage; // Not needed
// private NetworkConnection _conn; // Not needed
public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
{
StartCoroutine(API.GetOTPForUser(msg.user, userOTP => ReceiveOTPForUser(userOTP, conn, msg));
}
// Called when we receive the OTP from the API for the user trying to log in.
private void ReceiveOTPForUser(OTP userOTP, NetworkConnection conn, AuthRequestMessage msg)
{
... code continues
}
Oh, that's smart. I'll try this in a bit and accept this answer it if it works. Thank you!
Your answer
![](https://koobas.hobune.stream/wayback/20220613044141im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Executing an Action after a Coroutine has finished 2 Answers
How to shortcut a lambda expression through a function? 1 Answer
Waiting for and using output of a UnityEvent within coroutines 1 Answer
When to use 'delegate', 'event' or 'Action' ? 1 Answer
C# lambda call in for loop references to last object 3 Answers