Home > other >  Have the kotlin invoke() function return a Deferred from Coroutine
Have the kotlin invoke() function return a Deferred from Coroutine

Time:06-05

The invoke function allows a function to be called directly from the class.

How can I get this to work with a Coroutine Deferred result?

I have tried below but am getting Type mismatch Required: Deferred<List<MyModel>> Found: MyUseCase

class MyUseCase(
    private val repository: MyRepository,
) {
    suspend operator fun invoke(id: String): Deferred<List<MyModel>> =
        CoroutineScope(IO).async {
            repository.fetchApi(id)
        }
    }
val deferredResult: Deferred<List<MyModel>> = viewModelUseCases.myUseCase

CodePudding user response:

invoke allows an instance to be called as though it's a function, i.e. with parentheses. The invoke function you've written would be called by

val deferredResult: Deferred<List<MyModel>> = viewModelUseCases.myUseCase()
  • Related