How to iterate a simple callback with cursor in Java?

stevendesu :

Here's a simple example of my problem. Suppose I have an API that returns the following:

{
    cursor: 5,
    items: [
        { id: 0, value: "abc" },
        { id: 1, value: "abc" },
        { id: 2, value: "abc" },
        { id: 3, value: "abc" },
        { id: 4, value: "abc" }
    ]
}

Then after getting the last item:

{
    cursor: -1,
    items: [
        { id: 20, value: "abc" },
        { id: 21, value: "abc" },
        { id: 22, value: "abc" }
    ]
}

Now I have a Java function (written for me, I can't modify it) which takes a cursor and a callback object:

requestItems(5, new Callback() {
    @Override
    public void onResponse ( ItemResponse response )
    {
        response.getCursor(); // --> 10
        response.getItems(); // --> ArrayList<Item>
    }
});

I want to repeatedly call this method until there are no more items. The synchronous equivalent would be:

response = requestItems(0);
while (response.getCursor() > -1)
{
    response = requestItems(response.getCursor());
}

I tried using recursion, but this threw a compile-time error:

final Callback checkForMoreItems = new Callback() {
    @Override
    public void onResponse ( Response response )
    {
        if (reponse.getCursor() > -1)
            requestItems(response.getCursor(), checkForMoreItems); // <-- Error line
        else
            continueExecution();
    }
}

requestItems(0, checkForMoreItems);

This threw the error:

error: variable checkForMoreItems might not have been initialized

How are you supposed to handle recursive callbacks like this?

Severin Nitsche :

Try using this instead of checkForMoreItems:

requestItems(response.getCursor(), this);

This should resolve the issue, that the variable is not initialized, since it is technically an attribute of the anonymous class object you created. Another solution might be to factor the whole code out into its own class file, in which case you also would need to use this.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=420429&siteId=1