Home > front end >  Two chained invocations among several async invocations
Two chained invocations among several async invocations

Time:12-03

I have a method in my Kotlin app that looks like this:

coroutineScope{
      val aFetcher = async { a.fetch()}
      val bFetcher = async { b.fetch()}
      val cFetcher = async { c.fetch()}
      val dFetcher = async { d.fetch()}

      Merged(a.await(),b.await(),c.await(),d.await())
}      

The problem I am having is that I can't find a way to make one request depend on the other. In my case, I need for cFetcher to wait until bFetcher ended it's work before starting.

What's the right way to do that in Kotlin?

CodePudding user response:

Just make the part that should be synchronous, synchronous.

coroutineScope{
      val aFetcher = async { a.fetch() }
      val dFetcher = async { d.fetch() }
      val bResult = b.fetch()
      val cFetcher = async { c.fetch(bResult) }

      Merged(aFetcher.await(), bResult, cFetcher.await(), dFetcher.await())
}      

If you have more than one of these dependencies and want to run them in parallel you could do something like this I suppose:

coroutineScope{
      val aFetcher = async { a.fetch() }
      val dFetcher = async { d.fetch() }
      val bAndCFetcher = async {
        val bResult = b.fetch()
        bResult to c.fetch(bResult) 
      }

      Merged(aFetcher.await(), bAndCFetcher.await().first, bAndCFetcher.await().second, dFetcher.await())
}      
  • Related