[JAVA-4314] Observable head should take implicit ExecutionContext passed by consumer Created: 26/Sep/21  Updated: 27/Oct/23  Resolved: 29/Sep/21

Status: Closed
Project: Java Driver
Component/s: Scala
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Unknown
Reporter: Scott Rice Assignee: Ross Lawley
Resolution: Works as Designed Votes: 0
Labels: external-user, scala
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Right now, Observable head hard codes an ExecutionContext. It would be preferable if library consumers could pass in an ExecutionContext of their choosing:

  def head()(implicit ec: ExecutionContext): Future[T] = {
    headOption().map {
      case Some(result) => result
      case None         => null.asInstanceOf[T] // scalastyle:ignore null
    }
  }



 Comments   
Comment by Scott Rice [ 28/Sep/21 ]

Ahh, thank you. Yes, observeOn works for my needs. This ticket can be closed.

Comment by Ross Lawley [ 28/Sep/21 ]

Hi scott.rice@rallyhealth.com,

Custom execution contexts can be set on the Obervable like so: observable.observeOn(context).

This allows fine grained support for the context to use and allows different observable transformations to use their own context for example:

  it should "should be able to use custom execution contexts" in {
    var originalThreadId: Long = 0
    var observeOnThreadId1: Long = 0
    var observeOnThreadId2: Long = 0
    val ctx1 = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(5))
    val ctx2 = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(5))
 
    Await.result(
      observable()
        .map((i: Int) => {
          originalThreadId = Thread.currentThread().getId
          i
        })
        .observeOn(ctx1)
        .map((i: Int) => {
          observeOnThreadId1 = Thread.currentThread().getId
          i
        })
        .observeOn(ctx2)
        .map((i: Int) => {
          observeOnThreadId2 = Thread.currentThread().getId
          i
        })
        .toFuture(),
      Duration(10, TimeUnit.SECONDS)
    )
    ctx1.shutdown()
    ctx2.shutdown()
 
    originalThreadId should not be observeOnThreadId1
    observeOnThreadId1 should not be observeOnThreadId2
  }

I hope that feature meets your needs.

Ross

Generated at Thu Feb 08 09:01:45 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.