Return a CompletableFuture from a coroutine outside a suspending function

I am using a Java library (Graphql) where I need to override a method that returns a CompletableFuture and my method shouldn’t be marked as suspend.

Before coroutines 0.3 I had the following code:

class CategoryResolver(private val itemRepository: ItemRepository) : GraphQLResolver<Category> {

fun items(category: Category): CompletableFuture<List<Item>> = future {
    itemRepository.getItemsByCategoryId(category.id)
    }
}

Is there any way to return a CompletableFuture outside a suspending function without using the GlobalScope ?
Otherwise what would be the best way to go about this ?

1 Like

GlobalScope is a good choice for your use case

2 Likes

But you lose the coroutineContext from the parent suspend function that is calling you

It’s not a suspend method. The caller likely not a suspend method and has no coroutineContext.

If the method were being called from a suspend method, it would just suspend itself instead of returning CompletableFuture.