Search code examples
androidmultithreadingrx-javarx-java2

Specific scheduler’s threads for tasks each task should have its own scheduler’s thread


I'd like to make specific scheduler’s threads for tasks so that each task should have its own scheduler’s thread. How we could achieve this?

  • subject_1.onNext(task) -> Emit Task_1 on Scheduler's thread-1
  • subject_1.onNext(task) -> Emit Task_2 on Scheduler's thread-2

When work is finished, emit the task and receive it on the same Scheduler's thread.

  • subject_1.filter(task) -> Starts working with Task_1 on Scheduler's thread-1
  • subject_1.filter(task) -> Starts working Task_2 on Scheduler's thread-2

Pseudo code:

// Filter a task A on a Task-1-Thread, filter a task B on a Task-2-Thread, and so on..
return Single
        .just(task)
        .doOnNext { subject_1.onNext(task) } // Emit a task A on a caller's thread
        .observeOn(scheduler)
        .flatMap {
            subject_2
                    // Received on Task-{x}-Thread
                    .filter { doSomeStuff() } <- Release Task-{x}-Thread

subject_1
  .flatmap {}
  .observeOn(scheduler)
  .doOnNext { subject_2.onNext(task) } // Emit a task A on task a specific thread: Task-{x}-Thread
  .subscribe()

I am looking for something like this:

Single.just(task).observeOn(printingScheduler, task)


Solution

  • It sounds like you're looking for Schedulers.newThread():

    Returns a default, shared Scheduler instance that creates a new Thread for each unit of work.