Question

I want to make an API(node.js) with a get function. The module I use supports a write, and all incoming data is emitted by an event which I can subscribe too. The underlying system is based on polling.

But I also want to add pollers that write (using setInterval). When I add an listener for requesting the rpm, I get the RPM information every second. When I call a get at the same time for vss, it's possible that the data.name and type don't match. And that messes up my get for now.

So basically, what could I fill in the else block, and what is best practice? Or is this whole design a bad practice? Should a get not be supported in this case?

function get(type, callback) {
    sp.once('dataReceived', function (data) {
        if(data.name === type) {
            switch (data.name) {
                case "rpm":
                    callback(new RPMEvent(data.value));
                    break;
                case "vss":
                    callback(new SpeedEvent(data.value));
                    break;
                default:
                    console.log('Not supported yet.');
                    break;
            }
        } else {
            console.log('Collision with poller and get. Not supported yet.');
            //What to do here? I should addlistener again?
        }
    });

    sp.requestValueByName(type);
}

The 'dataReceived' event can be emitted more because of pollers on different variables (rpm/vss). How to get the right value for the get?

The longer I think about it, the more I think I should not support a get function while this dataReceived event is triggered by pollers too.

Was it helpful?

Solution

Solved it. I'm removing the listener when there is a match, and I'm not using once anymore.

function get(type, callback) {
    var getMessageHandler = function (data) {
        if(data.name === type) {
            switch (data.name) {
                case "rpm":
                    callback(new RPMEvent(data.value));
                    break;
                case "vss":
                    callback(new SpeedEvent(data.value));
                    break;
                default:
                    console.log('Not supported yet.');
                    break;
            }
            this.removeListener('dataReceived', getMessageHandler);
        } else {
            console.log('Collision with listener and get. Not supported yet.');
            //Do nothing, let the next thing come in. Will be caught by generalHandler.
        }
    };

    sp.on('dataReceived', getMessageHandler);

    //Request value after callback.
    sp.requestValueByName(type);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top