Skip to content

Instantly share code, notes, and snippets.

@Eldhopj
Created August 11, 2022 04:41
Show Gist options
  • Save Eldhopj/1ca6e6424c166a6082d7216c4f1644e3 to your computer and use it in GitHub Desktop.
Save Eldhopj/1ca6e6424c166a6082d7216c4f1644e3 to your computer and use it in GitHub Desktop.
suspendCoroutine { Convert callbacks into suspend functions }
private suspend fun singleValueEvent((ref: DatabaseReference ,onCancellation: CancellationCallback = {}),onCancellation: CancellationCallback = {}): DataResponse<DataSnapshot> {
return suspendCancellableCoroutine { continuation -> // can use suspendCoroutine not worry about cancellation
val valueEventListener = object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {
continuation.resume(DataResponse.Error(error.toException()), onCancellation) // setting data
}
override fun onDataChange(snapshot: DataSnapshot) {
continuation.resume(DataResponse.Changed(snapshot), onCancellation)
}
}
ref.addListenerForSingleValueEvent(valueEventListener)
continuation.invokeOnCancellation { ref.removeEventListener(valueEventListener) } // do things on cancellation of coroutine
}
}
fun getData(){
lifecycleScope.launch {
val result = singleValueEvent(refrence)
return when (result) {
is DataResponse.Changed -> {
}
is DataResponse.Error -> {
}
}
}
sealed class DataResponse<T> {
data class Changed<T>(val data: T) : DataResponse<T>()
data class Error<T>(val error: Exception) : DataResponse<T>()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment