টাস্ক API

গুগল প্লে পরিষেবাগুলিতে অ্যাসিঙ্ক্রোনাস অপারেশন পরিচালনার জন্য Task এপিআই হলো একটি আদর্শ পদ্ধতি। এটি পুরোনো PendingResult প্যাটার্নকে প্রতিস্থাপন করে অ্যাসিঙ্ক্রোনাস কলগুলি পরিচালনা করার একটি শক্তিশালী ও নমনীয় উপায় প্রদান করে। Task ব্যবহার করে আপনি একাধিক কলকে শৃঙ্খলিত করতে, জটিল ফ্লো পরিচালনা করতে এবং সুস্পষ্ট সাফল্য ও ব্যর্থতা হ্যান্ডলার লিখতে পারেন।

Handle task results

Many APIs in Google Play services and Firebase return a Task object to represent asynchronous operations. For example, FirebaseAuth.signInAnonymously() returns a Task<AuthResult> which represents the result of the sign-in operation. The Task<AuthResult> indicates that when the task completes successfully, it will return an AuthResult object.

কোনো Task ফলাফল নিয়ন্ত্রণ করতে, আপনি সেটির সফল সমাপ্তি, ব্যর্থতা বা উভয় ক্ষেত্রেই সাড়া দেয় এমন লিসেনার সংযুক্ত করতে পারেন:

Task<AuthResult> task = FirebaseAuth.getInstance().signInAnonymously();

সফলভাবে টাস্ক সম্পন্ন হওয়ার বিষয়টি পরিচালনা করতে, একটি OnSuccessListener সংযুক্ত করুন:

task.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
    @Override
    public void onSuccess(AuthResult authResult) {
        // Task completed successfully
        // ...
    }
});

To handle a failed task, attach an OnFailureListener :

task.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        // Task failed with an exception
        // ...
    }
});

একই লিসেনারে সাফল্য এবং ব্যর্থতা উভয়ই পরিচালনা করতে, একটি OnCompleteListener সংযুক্ত করুন:

task.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            // Task completed successfully
            AuthResult result = task.getResult();
        } else {
            // Task failed with an exception
            Exception exception = task.getException();
        }
    }
});

Manage threads

By default, listeners attached to a Task are run on the application main (UI) thread. This means that you should avoid doing long-running operations in listeners. If you need to perform a long-running operation, you can specify an Executor that is used to schedule listeners on a background thread.

// Create a new ThreadPoolExecutor with 2 threads for each processor on the
// device and a 60 second keep-alive time.
int numCores = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(numCores * 2, numCores *2,
        60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

task.addOnCompleteListener(executor, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        // ...
    }
});

Use activity-scoped listeners

When you need to handle task results within an Activity , it's important to manage the listeners' lifecycle to prevent them from being called when the Activity is no longer visible. To do this, you can use activity-scoped listeners. These listeners are automatically removed when the onStop method of your Activity is called, so that they won't be executed after the Activity is stopped.

Activity activity = MainActivity.this;
task.addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        // ...
    }
});

Chain tasks

যদি আপনি কোনো জটিল ফাংশনে এমন কিছু এপিআই ব্যবহার করেন যা Task অবজেক্ট রিটার্ন করে, তবে আপনি কন্টিনিউয়েশন ব্যবহার করে সেগুলোকে একসাথে চেইন করতে পারেন। এটি আপনাকে গভীরভাবে নেস্টেড কলব্যাক এড়াতে সাহায্য করে এবং একাধিক চেইন করা টাস্কের জন্য এরর হ্যান্ডলিং একত্রিত করে।

উদাহরণস্বরূপ, এমন একটি পরিস্থিতির কথা ভাবুন যেখানে আপনার doSomething একটি মেথড আছে যা একটি Task<String> রিটার্ন করে, কিন্তু প্যারামিটার হিসেবে এর একটি AuthResult প্রয়োজন। আপনি এই AuthResult অন্য একটি Task থেকে অ্যাসিঙ্ক্রোনাসলি পেতে পারেন:

public Task<String> doSomething(AuthResult authResult) {
    // ...
}

Task.continueWithTask মেথডটি ব্যবহার করে, আপনি এই দুটি টাস্ককে একসাথে যুক্ত করতে পারেন:

Task<AuthResult> signInTask = FirebaseAuth.getInstance().signInAnonymously();

signInTask.continueWithTask(new Continuation<AuthResult, Task<String>>() {
    @Override
    public Task<String> then(@NonNull Task<AuthResult> task) throws Exception {
        // Take the result from the first task and start the second one
        AuthResult result = task.getResult();
        return doSomething(result);
    }
}).addOnSuccessListener(new OnSuccessListener<String>() {
    @Override
    public void onSuccess(String s) {
        // Chain of tasks completed successfully, got result from last task.
        // ...
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        // One of the tasks in the chain failed with an exception.
        // ...
    }
});

Block a task

যদি আপনার প্রোগ্রামটি ইতিমধ্যেই একটি ব্যাকগ্রাউন্ড থ্রেডে চলছে, তাহলে আপনি কলব্যাক ব্যবহার না করে বর্তমান থ্রেডটিকে ব্লক করে কাজটি সম্পূর্ণ হওয়া পর্যন্ত অপেক্ষা করতে পারেন:

try {
    // Block on a task and get the result synchronously. This is generally done
    // when executing a task inside a separately managed background thread. Doing this
    // on the main (UI) thread can cause your application to become unresponsive.
    AuthResult authResult = Tasks.await(task);
} catch (ExecutionException e) {
    // The Task failed, this is the same exception you'd get in a non-blocking
    // failure handler.
    // ...
} catch (InterruptedException e) {
    // An interrupt occurred while waiting for the task to complete.
    // ...
}

কোনো টাস্ক সম্পূর্ণ হতে খুব বেশি সময় লাগলে, আপনার অ্যাপ্লিকেশনটি যাতে অনির্দিষ্টকালের জন্য আটকে না যায়, সেজন্য টাস্কটি ব্লক করার সময় আপনি একটি টাইমআউটও নির্দিষ্ট করে দিতে পারেন।

try {
    // Block on the task for a maximum of 500 milliseconds, otherwise time out.
    AuthResult authResult = Tasks.await(task, 500, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
    // ...
} catch (InterruptedException e) {
    // ...
} catch (TimeoutException e) {
    // Task timed out before it could complete.
    // ...
}

আন্তঃকার্যক্ষমতা

Task অন্যান্য প্রচলিত অ্যান্ড্রয়েড অ্যাসিঙ্ক্রোনাস প্রোগ্রামিং প্যাটার্নের সাথে ভালোভাবে কাজ করার জন্য ডিজাইন করা হয়েছে। এটিকে ListenableFuture এবং Kotlin coroutines-এর মতো অন্যান্য প্রিমিটিভগুলিতে রূপান্তর করা যায়, যা AndroidX দ্বারা প্রস্তাবিত , ফলে আপনি আপনার প্রয়োজন অনুসারে সেরা পদ্ধতিটি ব্যবহার করতে পারবেন।

Here's an example using a Task :

// ...
simpleTask.addOnCompleteListener(this) {
  completedTask -> textView.text = completedTask.result
}

Kotlin coroutine

Task সাথে Kotlin coroutine ব্যবহার করতে, আপনার প্রজেক্টে নিম্নলিখিত ডিপেন্ডেন্সিটি যোগ করুন এবং তারপরে Task থেকে রূপান্তর করার জন্য কোড স্নিপেটটি ব্যবহার করুন।

গ্রেডল (মডিউল-স্তরের build.gradle , সাধারণত app/build.gradle )
// Source: https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3'
Snippet
import kotlinx.coroutines.tasks.await
// ...
  textView.text = simpleTask.await()
}

Guava ListenableFuture

To use Guava ListenableFuture with Task , add the following dependency to your project and then use the code snippet to convert from a Task .

গ্রেডল (মডিউল-স্তরের build.gradle , সাধারণত app/build.gradle )
implementation "androidx.concurrent:concurrent-futures:1.2.0"
Snippet
import com.google.common.util.concurrent.ListenableFuture
// ...
/** Convert Task to ListenableFuture. */
fun <T> taskToListenableFuture(task: Task<T>): ListenableFuture<T> {
  return CallbackToFutureAdapter.getFuture { completer ->
    task.addOnCompleteListener { completedTask ->
      if (completedTask.isCanceled) {
        completer.setCancelled()
      } else if (completedTask.isSuccessful) {
        completer.set(completedTask.result)
      } else {
        val e = completedTask.exception
        if (e != null) {
          completer.setException(e)
        } else {
          throw IllegalStateException()
        }
      }
    }
  }
}
// ...
this.listenableFuture = taskToListenableFuture(simpleTask)
this.listenableFuture?.addListener(
  Runnable {
    textView.text = listenableFuture?.get()
  },
  ContextCompat.getMainExecutor(this)
)

RxJava2 Observable

আপনার পছন্দের অ্যাসিঙ্ক লাইব্রেরির পাশাপাশি নিম্নলিখিত ডিপেন্ডেন্সিটি আপনার প্রজেক্টে যোগ করুন এবং তারপরে একটি Task থেকে রূপান্তর করতে কোড স্নিপেটটি ব্যবহার করুন।

গ্রেডল (মডিউল-স্তরের build.gradle , সাধারণত app/build.gradle )
// Source: https://github.com/ashdavies/rx-tasks
implementation 'io.ashdavies.rx.rxtasks:rx-tasks:2.2.0'
Snippet
import io.ashdavies.rx.rxtasks.toSingle
import java.util.concurrent.TimeUnit
// ...
simpleTask.toSingle(this).subscribe { result -> textView.text = result }

Next steps