user10934825
user10934825

Reputation:

Equivalent of C# Action() delegate in Java?

C# introduces the concept of delegates, which represent methods that are callable without knowledge of the target object. In C# API I have a code:

var onReadyAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Connected));
var onTerminatedAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Disconnected));

where OnServerStateChangedSubject.OnNext(ServerState.Connected));is action witch signalize about server state. Question: how I can realize this in java? Code of method:

protected TradingClientWithQueue //Client class// KeepConnectAlive()
{
    var onReadyAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Connected));
    var onTerminatedAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Disconnected));

    if (Client == null)
    {
        Client = new TradingClientWithQueue();
        //events 
        Client.OnPacketReceived.Subscribe(OnDataPacketReceivedSubject.OnNext);
        ClientSubscribeOnTerminated(onTerminatedAction);

        Client.OnClientException.Subscribe(OnClientExceptionSubject.OnNext);
        Client.OnClientReady.Subscribe(isReady =>
        {
            AuthenticateClient();
            onReadyAction();
        });

        Client.Connect(Host, Port);
    }
    else
    {
        ClientSubscribeOnTerminated(onTerminatedAction);
        Client.Reconnect(Host, Port);
    }

    return Client;
}

Upvotes: 1

Views: 1443

Answers (1)

Michael
Michael

Reputation: 44200

The equivalent of a delegate is a functional interface.

Action is a function which consumes an item and returns void. The most obvious example of an equivalent functional interface would be Consumer<T>.

Upvotes: 1

Related Questions