Hi there. I couldn’t get why this code was being r...
# coroutines
u
Hi there. I couldn’t get why this code was being run on the main thread (why wouldn’t suspend function create its own thread):
Copy code
override suspend fun createAccount(
        name: String,
        avatarPath: String?
    ) : AccountEntity {

        Timber.d("Thread: ${Thread.currentThread().name}")

        return service.createAccount(name, avatarPath).let { response ->
            AccountEntity(
                id = response.id,
                name = response.name,
                avatar = response.avatar.toEntity()
            )
        }
    }
I launch inside
ViewModelScope
. Any help will be appreciated!
d
The
suspend
modifier only means "this function can suspend". It does not say anything about on which thread it will run.
u
@diesieben07, thanks. I actually run it in the following manner:
Copy code
abstract class BaseUseCase<out Type, in Params> where Type : Any {

    abstract suspend fun run(params: Params): Either<Throwable, Type>

    open operator fun invoke(
        scope: CoroutineScope,
        params: Params,
        onResult: (Either<Throwable, Type>) -> Unit = {}
    ) {
        val backgroundJob = scope.async { run(params) }
        scope.launch { onResult(backgroundJob.await()) }
    }

    object None
}
invoke()
gets
ViewModelScope
d
I am unfamiliar with Android, but I don't think ViewModelScope specifies a background thread either.
👍 1
l
g
viewModelScope always run on Main dispatcher by default
Use withContext(SomeDispatcher) {} to switch thread (you can use Dispatchers.IO)
I recommend you to read official coroutine guide how dispatchers work
u
thanks a lot