Skip to content

Commit

Permalink
fix: 콜백함수 코루틴으로 변경 및 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
easyhz committed Apr 9, 2024
1 parent e877064 commit 84207f4
Show file tree
Hide file tree
Showing 9 changed files with 110 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class UserRepositoryImpl
onSuccess.invoke()
}

override suspend fun signUp(user: UserForm, onSuccess: () -> Unit, onError: (String?) -> Unit) {
override suspend fun signUp(user: UserForm) {
try {
var uid = user.uid
var email = user.email
Expand All @@ -66,12 +66,11 @@ class UserRepositoryImpl
}

saveUser(uid, email, user.authProvider)
onSuccess.invoke()
} catch (e: FirebaseAuthException) {
onError(e.errorCode)
throw e
} catch (e: Exception) {
Log.e(this.javaClass.simpleName, "Sign Up Error: ${e.message}")
onError(e.unknownErrorCode())
throw e
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface UserRepository {
fun fetchLoginInfo(id: String) : Flow<UserInfo>
fun logout(onSuccess: () -> Unit)

suspend fun signUp(user: UserForm, onSuccess: () -> Unit, onError: (String?) -> Unit)
suspend fun signUp(user: UserForm)

suspend fun deleteUser(id: String, onSuccess: () -> Unit)
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,45 +7,38 @@ import com.easyhz.picly.domain.repository.album.AlbumRepository
import com.easyhz.picly.util.getImageSizes
import com.easyhz.picly.util.getImageUri
import com.google.firebase.Timestamp
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import javax.inject.Inject

class UploadUseCase
@Inject constructor(
private val repository: AlbumRepository
) {

fun writeAlbums(
sealed class UploadAlbumResult{
data class Success(val message: String): UploadAlbumResult()
data class Error(val errorMessage: String): UploadAlbumResult()
}
suspend fun writeAlbums(
ownerId: String,
tags: List<String>,
selectedImageList: List<GalleryImageItem>,
expireTime: Timestamp
): Flow<String> = flow {
): UploadAlbumResult = withContext(Dispatchers.IO) {
val album = createAlbum(ownerId, tags, selectedImageList, expireTime)
try {
var documentId = ""
repository.writeAlbums(album).collectLatest {
documentId = it.id
}
if (documentId.isBlank()) throw Exception()
val documentId = repository.writeAlbums(album).first().id
if (documentId.isBlank()) return@withContext UploadAlbumResult.Error("잠시 후 다시 시도해주세요.")
val imageUrls = repository.writeAlbumImages(documentId, selectedImageList.getImageUri()).first()
updateAlbum(documentId, album.copy(imageUrls = imageUrls.imageUrls, thumbnailUrl = imageUrls.thumbnailUrl))

val result = repository.updateAlbums(documentId, album.copy(imageUrls = imageUrls.imageUrls, thumbnailUrl = imageUrls.thumbnailUrl)).first()
return@withContext UploadAlbumResult.Success(result)
} catch (e: Exception) {
Log.e(this.javaClass.simpleName, "Error writing albums and images: ${e.message}")
throw e
UploadAlbumResult.Error("알 수 없는 오류가 발생하였습니다.")
}
}

private suspend fun FlowCollector<String>.updateAlbum(documentId: String, album: Album) {
val result = repository.updateAlbums(documentId, album).first()
emit(result)
}

private fun createAlbum(
ownerId: String,
tags: List<String>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,31 @@
package com.easyhz.picly.domain.usecase.user

import android.util.Log
import com.easyhz.picly.domain.model.user.UserForm
import com.easyhz.picly.domain.repository.user.UserRepository
import com.easyhz.picly.util.unknownErrorCode
import com.google.firebase.auth.FirebaseAuthException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject

class SignUpUseCase
@Inject constructor(
private val repository: UserRepository
){
suspend fun signUp(user: UserForm, onSuccess: () -> Unit, onError: (String?) -> Unit) = repository.signUp(user, onSuccess, onError)
sealed class SignUpResult {
data object Success: SignUpResult()
data class Error(val errorMessage: String): SignUpResult()
}
suspend fun signUp(user: UserForm): SignUpResult = withContext(Dispatchers.IO) {
try {
val result = repository.signUp(user)
return@withContext SignUpResult.Success
} catch (e: FirebaseAuthException) {
return@withContext SignUpResult.Error(e.errorCode)
} catch (e: Exception) {
Log.e(this.javaClass.simpleName, "SingUpUseCase Sign Up Error: ${e.message}")
return@withContext SignUpResult.Error(e.unknownErrorCode())
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import com.easyhz.picly.R
import com.easyhz.picly.databinding.FragmentUploadBinding
import com.easyhz.picly.domain.model.album.upload.gallery.GalleryImageItem
import com.easyhz.picly.domain.model.album.upload.gallery.GalleryImageItem.Companion.toGalleryImageItem
import com.easyhz.picly.domain.usecase.album.upload.UploadUseCase.UploadAlbumResult
import com.easyhz.picly.util.BlueSnackBar
import com.easyhz.picly.util.PICLY
import com.easyhz.picly.util.animateGrow
Expand All @@ -53,6 +54,9 @@ import com.easyhz.picly.view.dialog.Orientation
import com.easyhz.picly.view.navigation.NavControllerManager
import com.google.android.material.textfield.TextInputLayout
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@AndroidEntryPoint
Expand Down Expand Up @@ -232,7 +236,6 @@ class UploadFragment: Fragment() {
}
for (i in 0 until clipData.itemCount) {
val item = clipData.getItemAt(i).uri.toGalleryImageItem(requireActivity())
println("item> $item")
item?.let {
selectedImages.add(it)
}
Expand Down Expand Up @@ -354,13 +357,16 @@ class UploadFragment: Fragment() {
}
viewModel.selectedImageList.value?.let { imageList ->
loading.show(true)
viewModel.writeAlbums(
imageList,
binding.expireDateButton.text.toString(),
binding.expireTimeButton.text.toString(),
{ onFailure(it) }
) {
onSuccess(it)
CoroutineScope(Dispatchers.Main).launch {
val result = viewModel.writeAlbums(
imageList,
binding.expireDateButton.text.toString(),
binding.expireTimeButton.text.toString(),
)
when(result) {
is UploadAlbumResult.Success -> onSuccess(result.message)
is UploadAlbumResult.Error -> onFailure(result.errorMessage)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,11 @@ package com.easyhz.picly.view.album.upload
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.easyhz.picly.data.repository.user.UserManager
import com.easyhz.picly.domain.model.album.upload.gallery.GalleryImageItem
import com.easyhz.picly.domain.usecase.album.upload.UploadUseCase
import com.easyhz.picly.util.toFirebaseTimestamp
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
Expand All @@ -34,29 +28,18 @@ class UploadViewModel
_tags.value = emptyList()
}

fun writeAlbums(
suspend fun writeAlbums(
selectedImageList: List<GalleryImageItem>,
expiredDate: String,
expiredTime: String,
onFailure: (String) -> Unit,
onSuccess: (String) -> Unit,
) = viewModelScope.launch(Dispatchers.IO) {
val ownerId = UserManager.currentUser?.uid ?: run {
return@launch
}
uploadUseCase.writeAlbums(
expiredTime: String
): UploadUseCase.UploadAlbumResult {
val ownerId = UserManager.currentUser?.uid ?: return UploadUseCase.UploadAlbumResult.Error("")
return uploadUseCase.writeAlbums(
ownerId = ownerId,
tags = tags.value.orEmpty(),
selectedImageList = selectedImageList,
expireTime = "$expiredDate $expiredTime".toFirebaseTimestamp()
).catch { e ->
e.localizedMessage?.let { onFailure(it) }
}.collectLatest {
withContext(Dispatchers.Main) {
onSuccess(it)
}
}

)
}

fun addTag(tag: String) {
Expand Down
39 changes: 21 additions & 18 deletions app/src/main/java/com/easyhz/picly/view/user/LoginFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import com.easyhz.picly.data.firebase.Constants.AUTH_PROVIDER_GOOGLE
import com.easyhz.picly.data.repository.user.UserManager.initGoogle
import com.easyhz.picly.data.repository.user.UserManager.onGoogleSignInAccount
import com.easyhz.picly.databinding.FragmentLoginBinding
import com.easyhz.picly.domain.usecase.user.SignUpUseCase
import com.easyhz.picly.helper.PRIVACY_POLICY_URL
import com.easyhz.picly.helper.TERMS_OF_SERVICE_URL
import com.easyhz.picly.util.BlueSnackBar
Expand All @@ -29,9 +30,11 @@ import com.easyhz.picly.view.user.email.SignUpViewModel
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
Expand Down Expand Up @@ -127,24 +130,24 @@ class LoginFragment : Fragment() {
onFailure("${task.exception?.localizedMessage}")
return
}
if (task.result?.additionalUserInfo?.isNewUser == true) {
val user = task.result.user
user?.let { u ->
u.email?.let {
signUpViewModel.signUp(
requireActivity(),
email = it,
password = u.uid,
uid = u.uid,
authProvider = AUTH_PROVIDER_GOOGLE,
onSuccess = { onSuccess() }
) {
onFailure(it)
}
}
}
} else {
if (task.result?.additionalUserInfo?.isNewUser == false) {
onSuccess()
return
}
val user = task.result?.user ?: return
val email = user.email ?: return
CoroutineScope(Dispatchers.Main).launch {
val result = signUpViewModel.signUp(
requireActivity(),
email = email,
password = user.uid,
uid = user.uid,
authProvider = AUTH_PROVIDER_GOOGLE
)
when(result) {
is SignUpUseCase.SignUpResult.Success -> onSuccess()
is SignUpUseCase.SignUpResult.Error -> onFailure(result.errorMessage)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@ import com.easyhz.picly.R
import com.easyhz.picly.data.firebase.AuthError
import com.easyhz.picly.data.firebase.Constants.AUTH_PROVIDER_EMAIL
import com.easyhz.picly.databinding.FragmentEmailLoginBinding
import com.easyhz.picly.domain.usecase.user.SignUpUseCase
import com.easyhz.picly.util.BlueSnackBar
import com.easyhz.picly.util.user.setEmailField
import com.easyhz.picly.util.user.setPasswordField
import com.easyhz.picly.view.dialog.LoadingDialog
import com.easyhz.picly.view.navigation.NavControllerManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@AndroidEntryPoint
class SignUpFragment :Fragment() {
Expand Down Expand Up @@ -63,14 +67,17 @@ class SignUpFragment :Fragment() {
text = getString(R.string.sign_up)
setOnClickListener {
loading.show(true)
viewModel.signUp(
requireContext(),
email = binding.userField.emailField.editText.text.toString(),
password = binding.userField.passwordField.editText.text.toString(),
authProvider = AUTH_PROVIDER_EMAIL,
onSuccess ={onSuccess()}
) {
onFailure(it)
CoroutineScope(Dispatchers.Main).launch {
val result = viewModel.signUp(
requireContext(),
email = binding.userField.emailField.editText.text.toString(),
password = binding.userField.passwordField.editText.text.toString(),
authProvider = AUTH_PROVIDER_EMAIL,
)
when(result) {
is SignUpUseCase.SignUpResult.Success -> onSuccess()
is SignUpUseCase.SignUpResult.Error -> onFailure(result.errorMessage)
}
}
}
}
Expand Down
Loading

0 comments on commit 84207f4

Please sign in to comment.