samedi 25 novembre 2017

Dealing with nested callbacks

I ran into a case where I need to deal with the nested callbacks. See the Thing::process function. Second g_thing.onAfterWalk() callback will never get called because the parent one will destroy it as soon as it's done executing.

Thing g_thing;

void Thing::walk(int32_t x, int32_t y) {
    [..]
    // Walk finished. Run callback 
    if (m_afterWalk) {
        m_afterWalk();
        m_afterWalk = nullptr;
    }
}

void Thing::onAfterWalk(std::function<void(void)>& callback) {
    m_afterWalk = callback;
}

void Thing::process() {
    [..]
    g_thing.walk(1234, 1234);
    g_thing.onAfterWalk([]() {
        // After walking to 1234, 1234 walk to 4321, 4321
        g_thing.walk(4321, 4321);

        // After walking to 4321, 4321 so something else.
        // My actual problem... Callback within callback
        g_thing.onAfterWalk([]() { 
            std::cout << "Walking finished.\n";
        });
    });
}

How to deal with these kind of nested callbacks?

Should I have created a std::stack maybe with callbacks queue? What is the best approach?

Aucun commentaire:

Enregistrer un commentaire