Barmaley
Barmaley

Reputation: 16363

Koin: inject object returned by suspend function

I have object which created by suspend function like:

suspend fun someSuspendFunction(): MyPreciousObject

And I need to provide it for later injection using koin, like:

val myModule = module {
       single<MyPreciousObject> {
         //can call suspend function only from a coroutine or another suspend function
         someSuspendFunction() 
    }
}

Any ideas how to resolve this kind of situation? And please bear in mind that I can't change someSuspendFunction()

P.S. I'm using Kotlin JS/WASM environment, so runBlocking doesn't exist

Upvotes: 1

Views: 424

Answers (1)

Gary Archer
Gary Archer

Reputation: 29316

One DI pattern I have often used is a holder object that you can inject anywhere:

class MyPreciousObjectHolder
{
   var value: MyPreciousObject? = null
}

Then proceed as follows:

  • Make the holder object injectable
  • Resolve it in some kind of filter object that runs before your module and which can run a suspend operation to set the value
  • Your module then receives a holder with a populated value

I am no expert on koin though, so I cannot say for sure that this will work in that tech stack.

Upvotes: 1

Related Questions