Created
August 11, 2022 04:41
-
-
Save Eldhopj/1ca6e6424c166a6082d7216c4f1644e3 to your computer and use it in GitHub Desktop.
suspendCoroutine { Convert callbacks into suspend functions }
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
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 | |
} | |
} |
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
fun getData(){ | |
lifecycleScope.launch { | |
val result = singleValueEvent(refrence) | |
return when (result) { | |
is DataResponse.Changed -> { | |
} | |
is DataResponse.Error -> { | |
} | |
} | |
} |
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
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