Home > Software engineering >  Is it necessary to use .flowOn(Dispatchers.IO) inside repository class?
Is it necessary to use .flowOn(Dispatchers.IO) inside repository class?

Time:08-24

I'm trying to implement One Tap, so I have created this function:

override fun oneTapSgnInWithGoogle() = flow {
    try {
        emit(Result.Loading)
        val result = oneTapClient.beginSignIn(signInRequest).await()
        emit(Result.Success(result))
    } catch (e: Exception) {
        emit(Result.Error(e.message))
    }
}
//.flowOn(Dispatchers.IO)

And some programmer told me that I need to add .flowOn(Dispatchers.IO) to the above function, so it can be correct. My code work correct without it. Here is how I call this function in the ViewModel:

fun oneTapSignIn() = viewModelScope.launch {
    repo.oneTapSignInWithGoogle().collect { response ->
        oneTapSignInResponse = response
    }
}

Is it really necessary to do that? I'm really confused.

CodePudding user response:

You're calling beginSignIn which returns a Task, so it does its own stuff in the background. Now Task.await is suspending, not blocking, so it won't block the current thread while waiting for the task.

Therefore, the body of your flow doesn't contain any blocking stuff, so there is no reason to use flowOn(Dispatchers.IO) here.

  • Related