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!
Share Improve this question edited Feb 8 at 17:19 Cipri asked Feb 3 at 20:44 CipriCipri 2233 silver badges18 bronze badges 1- 2 I reverted your latest edit. Please don't ask multiple (different) questions at once, ask separate questions instead. Also, please don't substantially modify your question after an answer was given that would invalidate it. – tyg Commented Feb 8 at 2:25
1 Answer
Reset to default 3You 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.