How can I load data from Firestore in my Jetpack Compose project?

Viewed 1000

I have this project that I'm migrating to compose and I can't load the data from Firestore in the TextField. With the view system I could reference it and it uploaded automatically but with compose I'm unable to load. Below is the compose page and the FirestoreClass.

class ProfileFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

            FirestoreClass().loadUserDataOnProfile()

                return ComposeView(requireContext()).apply {
            setContent {
                ReiDoFifaTheme {

                        Column(
                            modifier = Modifier
                                .padding(16.dp)
                        ) {
                            Image(
                                modifier = Modifier
                                    .padding(top = 24.dp, bottom = 24.dp)
                                    .align(Alignment.CenterHorizontally),
                                painter = painterResource(R.drawable.ic_user_place_holder),
                                contentDescription = null
                            )
                            TextField(value = /*TODO*/ , onValueChange = { /*TODO*/ })
                        }
                    }
                }
    fun loadUserDataOnProfile(){
        firestore.collection(USERS)
            .document(getCurrentUserID())
            .get()
            .addOnSuccessListener { document ->
                val loggedUser = document.toObject(Player::class.java)
                ***
       }

I had a function *** called from on addOnSuccessListener that filled my views with the data on ProfileFragment. How do I do it?

1 Answers

Storing the new data to Kotlin Flow APIs

 fun loadUserDataOnProfile() : Flow<LoggedUser> = callbackFlow {
    firestore.collection(USERS)
        ...
        .addOnSuccessListener { document ->
            val loggedUser = document.toObject(Player::class.java)
            offer(loggedUser)
        }
    awaitClose { /* unregister firebase listener here */ }
 }

Then:

    ...
    return ComposeView(requireContext()).apply {
        setContent {
            val user: LoggedUser by  FirestoreClass().loadUserDataOnProfile().collectAsState(initial = /*DefaultLoggedUser*/)
            ReiDoFifaTheme {
               ...
                        TextField(value = user.name , onValueChange = { /*TODO*/ })
                    }
                
            }

Note: But for better, you should combine with the ViewModel

Related