How to create a my own com.google.android.gms.tasks.Task in android?

Viewed 989

I want to achieve the following in my code

fun addAsync(num1: Int, num2: Int): Task<Int> {
    var result: Task<Int> = //Task.fromResult(add(num1,num2))
    return result
}

fun add(num1: Int, num2:Int): Int {
    return num1+num2
}

here i want to know how to create a task from the result the way it is done in C#.

2 Answers

The correct way is use the TaskCompletionSource:

fun addAsync(num1: Int, num2: Int): Task<Int> {
    val t = TaskCompletionSource<Int>();

    // in some thread or whatever
    t.setResult(add(num1, num2))

    return t.task
}

fun add(num1: Int, num2:Int): Int {
    return num1+num2
}

Use Tasks.call(), passing an instance of Callable:

var result: Task<Int> = Tasks.call { 1 + 2 }

But that executes on the main thread. If you want another thread, pass an Executor:

val result: Task<Int> = Tasks.call(someExecutor, Callable {
    1 + 2
})
Related