I have a function that signs up a user and stores them in the Firestore database. For now, everything is happening inside the fragment but I would like to move it to the repo and connect via the view model.
fun signUp(){
val username = binding.signUpUsername.editText!!.text.toString()
val email = binding.singUpEmail.editText!!.text.toString()
val password = binding.signUpPassword.editText!!.text.toString()
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful){
task.result.user!!.sendEmailVerification().addOnCompleteListener{
val newUser = User(uid = task.result.user!!.uid, username=username)
lifecycleScope.launch{
repository.addUser(newUser)
}.invokeOnCompletion {
Log.d("sign_up", "Your registration is successful: ${task.result.user!!.uid}")
Toast.makeText(this, "Account has been created. Confirm your email.", Toast.LENGTH_SHORT).show()
auth.signOut()
startActivity(Intent(this, LoginMainActivity::class.java))
finish()
}
}
} else {
Log.d("sign_up", task.exception.toString())
}
}
}
suspend fun addUser(user: User) {
db.collection(Constants.USERS).document(user.uid).set(user).await()
}
My question is how to invoke suspend function addUser() inside my repo. Can I just create CoroutineScope inside my main function? Is it acceptable? I would like to do it correctly but I haven't found any solution.