Skip to content

Instantly share code, notes, and snippets.

@azlekov
Last active January 3, 2020 18:02
Show Gist options
  • Save azlekov/cc863443b6820f42a9efc98bff0b3195 to your computer and use it in GitHub Desktop.
Save azlekov/cc863443b6820f42a9efc98bff0b3195 to your computer and use it in GitHub Desktop.
Provide synchronous style invocation of Parse queries using suspend function and Kotlin 1.3 Coroutines
import androidx.lifecycle.LiveData
import bolts.Task
import com.parse.ParseObject
import com.parse.ParseQuery
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.reflect.KProperty
import kotlinx.coroutines.*
suspend fun <T> Task<T>.await(): T {
// fast path
if (isCompleted) {
val e = error
return if (e == null) {
if (isCancelled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
@Suppress("UNCHECKED_CAST")
result as T
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
onSuccess {
val e = error
if (e == null) {
@Suppress("UNCHECKED_CAST")
if (isCancelled) cont.cancel() else cont.resume(result as T)
} else {
cont.resumeWithException(e)
}
}
}
}
fun <T : ParseObject> ParseQuery<T>.liveData(): LiveData<List<T>> {
return object : LiveData<List<T>>() {
override fun onActive() {
findInBackground { items, error ->
if (error == null) {
GlobalScope.launch(Dispatchers.Main) {
value = items
}
}
}
}
override fun onInactive() {
super.onInactive()
if (isRunning) {
cancel()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment