Getting the first emitted item – blockingFirst()

The first blocking operator we are going discuss is the blockingFirst operator. This operator blocks the calling thread until the first item is emitted and returns it. The following is an ideal test case for blockingFirst(), where we are performing a sorting operation on Observable and we are testing it by checking if the first emitted item is the smallest. Please refer to the following code:

    @Test 
    fun `test with blockingFirst`() { 
      val observable = listOf(2,10,5,6,9,8,7,1,4,3).toObservable() 
            .sorted() 
     
      val firstItem = observable.blockingFirst() 
      assertEquals(1,firstItem) 
    } 

The test result is as follows:

In the program, we created an unsorted list of integers from 1 to 10 and created an Observable ...

Get Reactive Programming in Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.