https://kotlinlang.org logo
Title
a

allan.conda

07/20/2020, 10:51 AM
I need some help. I have 2 unrelated useCases sharing a common dependency, I want them to share the execution of their dependency if that’s possible, because it’s critical that the dependency is only called once. Is there a way to do this nicely with coroutines?
one idea is just make sure to call the dependency on App creation and cache the result before the usecases are executed, then the use cases simply accessed the cached value
b

bezrukov

07/20/2020, 11:03 AM
you can create async coroutine in commonDependency with start = lazy:
commonDependency { 
   // someScope needs to be injected, and it should live longer than useCaseA/useCaseB
   val resultDeferred = someScope.async(start = CoroutineStart.LAZY) {
      log("fetching result...")
      //
      result
   }

   suspend fun fetchResult() = resultDeferred.await()
}
👍 1