https://kotlinlang.org logo
#coroutines
Title
# coroutines
u

ubu

10/25/2019, 11:30 AM
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

diesieben07

10/25/2019, 11:31 AM
The
suspend
modifier only means "this function can suspend". It does not say anything about on which thread it will run.
u

ubu

10/25/2019, 11:33 AM
@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

diesieben07

10/25/2019, 11:36 AM
I am unfamiliar with Android, but I don't think ViewModelScope specifies a background thread either.
👍 1
l

louiscad

10/25/2019, 12:36 PM
g

gildor

10/25/2019, 12:38 PM
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

ubu

11/06/2019, 12:44 PM
thanks a lot
3 Views