Skip to content

Instantly share code, notes, and snippets.

View yashovardhan99's full-sized avatar
🎯
Focusing

Yashovardhan Dhanania yashovardhan99

🎯
Focusing
View GitHub Profile
@yashovardhan99
yashovardhan99 / User.kt
Last active July 15, 2020 18:16
Firebase MVVM User
@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")!!
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 / FirebaseProfileService.kt
Last active August 18, 2020 04:56
Firebase MVVM Profile Service 2
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")
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)