2

I am in need that i need to start the coroutines from rxkotlin chain, But am i not sure whether this is right or wrong, to start a coroutines from the rx chain i use runblocking to start the suspend methods
Example

Single.just(someOperation())
   .map{
     someMethod(it)
   }
  .flatMap{
    startCoroutines(suspend { someOpeartions() } ) // i will be starting the coroutines here
  }

Coroutines

fun startCoroutines(suspendingObj : suspend () -> Any){
  runBlocking(newFixedThreadPoolContext(1,"Thread")){
       suspendingObj.invoke()
  }
}

Is this above code is correct way of doing it or is there is any other way to achieve this ? Can anyone help me out with this

4
  • Why do you need coroutines if it's already inside the chain? I guess it should either rx or coroutines. Commented Jul 19, 2019 at 5:06
  • @TentenPonce is this wrong way of doing if so why ? Commented Jul 19, 2019 at 5:07
  • rx is already asynchronous, why do you want to use coroutines inside it? if your goal is to change thread, it is already supported on rx .observeOn(). You can just instead of suspend, just make it rx and add it on your current chain. Commented Jul 19, 2019 at 5:09
  • Blocking is almost never a good choice, Rx or no Rx. There exist converters and builders that can bridge the two approaches. For example rxSingle. Commented Jul 19, 2019 at 8:13

1 Answer 1

1

This code chunk is fundamentally wrong.

  1. In your case it is really not necessary to use Coroutines, because you can easily change Rx thread before flatMap with observeOn and pass any Scheduler you want (like IO).
  2. Kotlin Coroutines were designed to avoid Threads, because creating Threads is a very expensive operation. And your function startCoroutines creates a new thread for every operation which makes no sense and potentially will cause overflow. You can read more about it here: Difference between a "coroutine" and a "thread"?
  3. You should always try to find a better system design before deciding using runBlocking. Blocking threads is never a good idea.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.