class LifecycleAgentStatusMonitor implements AgentStatusMonitor {

    @Override
    public Observable<AgentStatus> monitor() {
        return agentManagementService.events(false).flatMap(event -> {
            if (event instanceof AgentInstanceUpdateEvent) {
                AgentInstance agentInstance = ((AgentInstanceUpdateEvent) event).getAgentInstance();
                knownInstances.put(agentInstance.getId(), agentInstance);
                return Observable.just(statusOf(agentInstance));
            }
            if (event instanceof AgentInstanceRemovedEvent) {
                // As AgentInstanceRemovedEvent does not contain AgentInstance value, which is required in AgentStatus
                // we have to cache it, and tweak when the AgentInstanceRemovedEvent event is received.
                AgentInstance agentInstance = knownInstances.remove(((AgentInstanceRemovedEvent) event).getAgentInstanceId());
                if (agentInstance != null) {
                    return Observable.just(toTerminatedEvent(agentInstance));
                }
            }
            return Observable.empty();
        });
    }

    @Inject public  LifecycleAgentStatusMonitor(AgentManagementService agentManagementService, TitusRuntime titusRuntime);

}