Nurseyit Tursunkulov
Nurseyit Tursunkulov

Reputation: 9380

withContext<Unit> what it does? Coroutines

I am researching blueprints sample by google https://github.com/googlesamples/android-architecture/tree/todo-mvvm-live-kotlin in datasource layer they use 2 different ways to handle suspend function :

withContext<Unit>(ioDispatcher) {
  ....
}

and such:

withContext(ioDispatcher) {
    ...
}

what is the difference between them?

Upvotes: 1

Views: 201

Answers (1)

Valeriy Katkov
Valeriy Katkov

Reputation: 40602

withContext has a generic argument, which specifies the return type of the lambda that you pass in. If the lambda doesn't return anything, it would be better to explicitly use Unit returns type, in this case there will be a warning, if your lambda returns something by mistake.

// No warnings, the result has Int type, which has been inferred automatically
val result = withContext(ioDispatcher) { 123 }

// "The expression is unused" warning, because the lambda should't return anything
val result = withContext<Unit>(ioDispatcher) { 123 }

Upvotes: 1

Related Questions