Skip to content

Instantly share code, notes, and snippets.

Avatar
🎯
Focusing

Yashovardhan Dhanania yashovardhan99

🎯
Focusing
View GitHub Profile
View FirebaseProfileService.kt
fun getPosts(userId: String): Flow<List<Post>> {
val db = FirebaseFirestore.getInstance()
return callbackFlow {
val listenerRegistration = db.collection("users")
.document(userId)
.collection("posts")
.addSnapshotListener { querySnapshot: QuerySnapshot?, firebaseFirestoreException: FirebaseFirestoreException? ->
if (firebaseFirestoreException != null) {
cancel(message = "Error fetching posts",
cause = firebaseFirestoreException)
@yashovardhan99
yashovardhan99 / FirebaseProfileService.kt
Last active Aug 18, 2020
Firebase MVVM Profile Service 2
View FirebaseProfileService.kt
suspend fun getFriends(userId: String): List<User> {
val db = FirebaseFirestore.getInstance()
return try {
db.collection("users")
.document(userId)
.collection("friends").get().await()
.documents.mapNotNull { it.toUser() }
} catch (e: Exception) {
Log.e(TAG, "Error getting user friends", e)
FirebaseCrashlytics.getInstance().log("Error getting user friends")
View FirebaseProfileService.kt
object FirebaseProfileService {
private const val TAG = "FirebaseProfileService"
suspend fun getProfileData(userId: String): User? {
val db = FirebaseFirestore.getInstance()
return try {
db.collection("users")
.document(userId).get().await().toUser()
} catch (e: Exception) {
Log.e(TAG, "Error getting user details", e)
FirebaseCrashlytics.getInstance().log("Error getting user details")
@yashovardhan99
yashovardhan99 / User.kt
Last active Jul 15, 2020
Firebase MVVM User
View User.kt
@Parcelize
data class User(val userId: String, //Document ID is actually the user id
val name: String,
val bio: String,
val imageUrl: String) : Parcelable {
companion object {
fun DocumentSnapshot.toUser(): User? {
try {
val name = getString("name")!!