Home > Back-end >  How to intrepret this C# lambda example
How to intrepret this C# lambda example

Time:11-19

I am really struggling to understand what is going on with this code, what does the single line lambda return if anything ? I am unclear on what that 3rd argument is going to be ?

   public Task<StatusMessage> MarketSubscription(MarketSubscriptionMessage message)
    {
        int id = NextId();
        message.Id = id;
        message.Op = REQUEST_MARKET_SUBSCRIPTION;
        var newSub = new SubscriptionHandler<MarketSubscriptionMessage, ChangeMessage<MarketChange>, MarketChange>(id, message, false);

        return SendMessage(new RequestResponse(id, message, 
                            success => MarketSubscriptionHandler = newSub));
    }

For info the other method is

public RequestResponse(int id, RequestMessage request, Action<RequestResponse> onSuccess)
{
    Id = id;
    Request = request;
    OnSuccess = onSuccess;
}

I would be most grateful if anyone could explain how to intrepret that last complex line. Thanks.

CodePudding user response:

Well RequestResponse :

public RequestResponse(int id, RequestMessage request, Act ion<RequestResponse> onSuccess)
{
    Id = id;
    Request = request;
    OnSuccess = onSuccess;
}

takes 3 argumenta, and ID, a message and an Action to call, presumably when some reply is received . The Action takes an argument that contains the response, an instance of RequestResponse.

The calling code sets up this callback (ACtion) here

new RequestResponse(id, message, 
                        success => MarketSubscriptionHandler = newSub)

the last argument is the Action. It is a bit odd in that it doesnt do anything with the response, nor does it run any code. It simply sets MarketSubscriptionHandler (presumably a class member variable) to newSub. newSub is

    var newSub = new SubscriptionHandler<MarketSubscriptionMessage, ChangeMessage<MarketChange>, MarketChange>(id, message, false);

My guess is that after the code you show exits another piece of code does something with MarketSubscriptionHandler

CodePudding user response:

In your example code, the 3rd argument to SendMessage() is an action named onSuccess, which appears to be a delegate that is invoked at a later time when/if the request has succeeded.

This usage of an action allows the caller of SendMessage() to specify any action they like which receives RequestResponse as an argument. A caller could specify an action to log something, execute another method, etc, or in this case, assign newSub as the MarketSubscriptionHandler.

Basically what's happening is:

  1. The message is sent via SendMessage()
  2. When response is received, SendMessage() checks to see if onSuccess should be invoked.
  3. If response is deemed successful,onSuccess is invoked (which in this case assigns newSub as the MarketSubscriptionHandler).
  • Related