File indexing completed on 2025-02-02 04:47:48

0001 /*
0002  * SPDX-FileCopyrightText: 2018 Erik Duisters <e.duisters1@gmail.com>
0003  *
0004  * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005  */
0006 
0007 package org.kde.kdeconnect.async;
0008 
0009 import androidx.annotation.NonNull;
0010 
0011 import java.util.concurrent.atomic.AtomicLong;
0012 
0013 public abstract class BackgroundJob<I, R> implements Runnable {
0014     private static final AtomicLong atomicLong = new AtomicLong(0);
0015     protected volatile boolean canceled;
0016     private BackgroundJobHandler backgroundJobHandler;
0017     private final long id;
0018 
0019     protected final I requestInfo;
0020     private final Callback<R> callback;
0021 
0022     public BackgroundJob(I requestInfo, Callback<R> callback) {
0023         this.id = atomicLong.incrementAndGet();
0024         this.requestInfo = requestInfo;
0025         this.callback = callback;
0026     }
0027 
0028     void setBackgroundJobHandler(BackgroundJobHandler handler) {
0029         this.backgroundJobHandler = handler;
0030     }
0031 
0032     public long getId() { return id; }
0033     public I getRequestInfo() { return requestInfo; }
0034 
0035     public void cancel() {
0036         canceled = true;
0037         backgroundJobHandler.cancelJob(this);
0038     }
0039 
0040     public boolean isCancelled() {
0041         return canceled;
0042     }
0043 
0044     public interface Callback<R> {
0045         void onResult(@NonNull BackgroundJob job, R result);
0046         void onError(@NonNull BackgroundJob job, @NonNull Throwable error);
0047     }
0048 
0049     protected void reportResult(R result) {
0050         backgroundJobHandler.runOnUiThread(() -> {
0051             callback.onResult(this, result);
0052             backgroundJobHandler.onFinished(this);
0053         });
0054     }
0055 
0056     protected void reportError(@NonNull Throwable error) {
0057         backgroundJobHandler.runOnUiThread(() -> {
0058             callback.onError(this, error);
0059             backgroundJobHandler.onFinished(this);
0060         });
0061     }
0062 }