Where does the Callback object come from in the ListenableWorker example?
Asked Answered
I

1

11

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.

Intoxicating answered 12/6, 2019 at 7:57 Comment(1)
You have one in your code already. If you don't, you don't need a callback-to-future-adapter. The trick here is that you can use code that you call like downloadAsynchronously("https://www.google.com", callback) with whatever callback that code wants and still turn it into a future so that you can wait on the completion of that download in this example.Getz
H
15

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;
    });
}
Heisler answered 12/6, 2019 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.