Skip to content

Instantly share code, notes, and snippets.

@ForceTower
Last active September 24, 2020 22:13
Show Gist options
  • Save ForceTower/c55b1703086a9dda45223530553bf222 to your computer and use it in GitHub Desktop.
Save ForceTower/c55b1703086a9dda45223530553bf222 to your computer and use it in GitHub Desktop.
Usefull Firebase Kotlin suspend stuff
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.storage.CancellableTask
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.sendBlocking
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
suspend fun <T> Task<T>.suspend() = suspendCancellableCoroutine<T> { continuation ->
this.addOnCompleteListener {
if (it.isSuccessful) {
continuation.resume(it.result!!)
} else {
continuation.resumeWithException(it.exception!!)
}
}
continuation.invokeOnCancellation {
if (this is CancellableTask) { this.cancel() }
}
}
@ExperimentalCoroutinesApi
fun DocumentReference.asFlow() = callbackFlow {
val subscription = [email protected] { value, error ->
if (value != null) sendBlocking(value)
else if (error != null) throw error
}
awaitClose { subscription.remove() }
}
@ExperimentalCoroutinesApi
fun CollectionReference.asFlow() = callbackFlow {
val subscription = [email protected] { value, error ->
if (value != null) sendBlocking(value)
else if (error != null) throw error
}
awaitClose { subscription.remove() }
}
@ExperimentalCoroutinesApi
fun currentFirebaseUser() = callbackFlow {
val listener = FirebaseAuth.AuthStateListener {
sendBlocking(it)
}
authentication.addAuthStateListener(listener)
awaitClose { authentication.removeAuthStateListener(listener) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment