Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the Callback object come from in the ListenableWorker example?

The Android developer docs show an example of how to use a ListenableWorker. However, despite having added councurrent-futures to my project, I see now relevant Callback object as used in the docs:

 @NonNull
    @Override
    public ListenableFuture<Result> startWork() {
        return CallbackToFutureAdapter.getFuture(completer -> {
            Callback callback = new Callback() {
            ...
            }

Can anyone point me in the right direction? There doesnt seem to be a Callback class in androidx.concurrent.callback at all.

this is literally the only code sample I can find that uses CallbackToFutureAdapter.getFuture at all.

like image 502
ardevd Avatar asked Feb 03 '23 18:02

ardevd


1 Answers

Looking at the documentation to a similar API, it looks to me that Callback is not an API in itself but a generic representation of any operation with results.

https://developer.android.com/reference/androidx/concurrent/futures/CallbackToFutureAdapter.html

As an example, you could define the callback as follows,

interface AsyncCallback  {
   void onSuccess(Foo foo);
   void onError(Failure failure);
}

And the startWork method as follows

@Override
public ListenableFuture<Result> startWork() {
    return CallbackToFutureAdapter.getFuture(completer -> {
        AsyncCallback callback = new AsyncCallback() {
            int successes = 0;

            @Override
            public void onError(Failure failure) {
                completer.setException(failure.getException());
            }

            @Override
            public void onSuccess(Foo foo) {
                completer.set(Result.success());
            }
        };

        for (int i = 0; i < 100; ++i) {
            downloadAsynchronously("https://www.google.com", callback);
        }
        return callback;
    });
}
like image 176
Dinesh Avatar answered Feb 06 '23 14:02

Dinesh