Help with resolving call multiple times (Call keepAlive)

Hi!

I was hoping for a little further explanation than what this link provides:

In my plugin I will be downloading multiple files. In the Android project, I have a Java Task with an on completion callback, which is where my calls resolve. I wanted to set the keepalive to true, resolve multiple calls for each file downloaded, and then on the LAST file, perform the final call.resolve().

I can confirm that the call.isKeptAlive() is true up until the last call.resolve(), however my client only ever receives the first call.resolve(). Am I doing something wrong? If the client code is something like:

await someFunc(params)
    .then((response) => { console.log(response) })
    .catch((err) => { console.log(err) })

Then shouldn’t I be receiving multiple console logs, one for each successful call.resolve?

EDIT: Here’s an example of the Java:

@PluginMethod
public void func1(PluginCall call, Boolean keepAlive) {
    // ... do some things ...

    if (keepAlive) {
        call.resolve(myData);
    }
    else {
        call.setKeepAlive(false);
        call.resolve(myFinalData);
    }
}

@PluginMethod
public void func2(PluginCall call) {
    call.setKeepAlive(true);

    // ... do some things ...

    for (int i = 0; i == someNumber; i++) {
        Boolean step = (i == someNumber);

        // step is false on the last iteration
        func1(call, step)
    }
}

I can confirm the call.isKeptAlive() is true up until the last call.resolve()… but my client only console logs the first call.resolve(). Any ideas?

In JavaScript a promise can only be resolved once. So you cannot use someFunc(params).then(...) if you need multiple responses. You need to use a callback function instead.

The method you’re implementing is of type 3 (callback) as described in Method Types. So you need to declare it as such in the native code and then use it as const callbackId = await someFunc(params, (response) => {...}).

For an example you can take a look at the code of the geolocation plugin and its watchPosition method.

Another way to achieve something similar would be Plugin Events.

PS: I suggest to not mix async/await with.then/.catch when dealing with promises in JavaScript.

5 Likes