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

3

5

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#.

Merchandise answered 5/4, 2020 at 9:34 Comment(0)
S
9

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
}
Statocyst answered 2/9, 2020 at 23:27 Comment(1)
Thanks. You're a genius.Commensurate
M
1

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
})
M16 answered 6/4, 2020 at 1:48 Comment(1)
this method has been deprecated... which should be the new right way?Gaud
N
0

You can return a complete task with

Tasks.forResult()

you can find the docs here: https://developers.google.com/android/reference/com/google/android/gms/tasks/Tasks

Neutralization answered 9/5 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.