What I should use for live refresh data on my KMM application with Firestore DB?
Use ObserveAsState with:
userViewModel.userInfo.observeAsState(null).apply {
// view or edit document here
}
with userInfo LiveData:
val userInfo: LiveData<UserInfo?> = liveData {
try {
emitSource(repo.getUserProfile().flowOn(Dispatchers.IO).asLiveData(Dispatchers.Main))
}catch (_: Exception) { }
}
or to call directly userInfo from repository with collectAsState:
serViewModel.repo.getUserProfile().collectAsState(null).apply {
// view or edit document here
}
the getUserProfile() in repo looks like this:
fun getUserProfile(): Flow<UserInfo?> = flow {
firestore.collection("UserInfo").document(auth.currentUser!!.uid).snapshots.collect { user ->
emit(user.data<UserInfo>())
}
}
Both versions work, I just don’t know which is the best and fastest for live data sync on mobile. Any improvements are welcome.
2
Answers
LiveData is only needed when using the old view system in Android with XML layouts.
The modern approach is to use Flows. When you use Compose for the UI you use
collectAsState
(orcollectAsStateWithLifecycle
when you want it to be lifecycle-aware) to convert them into Compose State.In this case, you should continue to work with the one you are more comfortable with. However, in modern Android development, it’s more recommended to use Kotlin Flows, especially when you’re building an app using KMM.
Please also note that the
LiveData
is not tied in any way with Android views. LiveData is a data holder class that can be observed within a given lifecycle, no matter if you’re using views or composable functions to create the layouts.