Remove listener on listener method?

Is it safe to remove a listener on the method that listens?

Consider the following:

On key press I want to render the depth buffer onto an FBO and store it. So I need to do something once and it needs to be on the draw call from the main loop. I’m doing something like this:

void ofApp::onKeyPress(...)
{
    if(key == 's')
    {
        ofAddListener(ofEvents().draw, this, &ofApp::drawOnce);
    }
}


void ofApp::drawOnce()
{
    drawAndSave();
    ofRemoveListener(ofEvents().draw, this, &ofApp::drawOnce);
}

I’m getting weird OpenGL crashes every once in a while and I think it might be related. This is on of 0.8.4 btw.

this should be ok in both 0.8.4 and 0.9, the events use a recursive mutex and make a copy of the listeners while calling them to be completely sure that edge cases like this won’t crash.

apart from that the way you are doing it seems quite complicated. i would just set a flag to true and call drawOnce from draw if that flag is set which also makes the order much more obvious. you can even call drawOnce directly from the key event if you are drawing to an fbo

Thanks.

What’s the logic behind what needs to be drawn within the ofApp draw function though? It’s usually advised to make openGL calls only inside the draw function, is that a hard requirement or only for performance?

it’s really only for organizing the code better, that pattern comes from video games and similar systems where you usually update your physics system and then draw it. it also has an inpact on performance

in OF in particular if you draw outside of draw somethings might not be set but when you draw to an fbo the fbo sets the necesary buffers and the perspective matrix when you call begin so you can usually use it anywhere