I have a repository function that returns me the user profile:
private val repoScope = MainScope()
fun getProfile(): CommonFlow<User> =
firestore.collection("User").where{ "userID" equalTo auth.currentUser!!.uid }.snapshots
.mapLatest { users ->
users.documents.first().data<User>()
}
.shareIn(repoScope, SharingStarted.WhileSubscribed(5000), 1)
.asCommonFlow()
If I call getProfile() multiple times, it will create multiple connections to firestore or use only one. Is shareIn used as supposed?
this is how I normally use it:
val user = getProfile().first()
How can I handle potential errors when they occur? For example, if I’m not signed in yet, the application crashes. How can I resolve this issue?
Any improvements are welcome. Thanks for the help!
I have a repository function that returns me the user profile:
private val repoScope = MainScope()
fun getProfile(): CommonFlow<User> =
firestore.collection("User").where{ "userID" equalTo auth.currentUser!!.uid }.snapshots
.mapLatest { users ->
users.documents.first().data<User>()
}
.shareIn(repoScope, SharingStarted.WhileSubscribed(5000), 1)
.asCommonFlow()
If I call getProfile() multiple times, it will create multiple connections to firestore or use only one. Is shareIn used as supposed?
this is how I normally use it:
val user = getProfile().first()
How can I handle potential errors when they occur? For example, if I’m not signed in yet, the application crashes. How can I resolve this issue?
Any improvements are welcome. Thanks for the help!
You put it in a function that runs all of the code after the =
every time you call it, so it is generating a brand new instance of a SharedFlow every time.
A SharedFlow should be assigned to a val
property, which will be initialized only once, and then stored in a backing variable that it's retrieved from on every subsequent call to the property:
val profile: CommonFlow<User> =
firestore.collection("User").where{ "userID" equalTo auth.currentUser!!.uid }.snapshots
.mapLatest { users ->
users.documents.first().data<User>()
}
.shareIn(repoScope, SharingStarted.WhileSubscribed(5000), 1)
.asCommonFlow()
In Kotlin, if your function starts with "get
" and has no parameters, you are doing something wrong. Kotlin uses properties, not getters and setters, for getting and setting things that don't need other parameters. You can't create a getter that actually works correctly without creating a backing property, which would be a convoluted redundancy.