Last active
January 3, 2020 18:02
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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