C#引入了委托的概念,代表了无需知道目标对象即可调用的方法。 在C#API中,我有一个代码:
var onReadyAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Connected));
var onTerminatedAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Disconnected));
其中OnServerStateChangedSubject.OnNext(ServerState.Connected));
是动作,表明服务器状态。
问题:如何在Java中实现?
方法代码:
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;
}