The startWith operator

We got introduced to the startWith operator in the previous chapter, but there's still a lot to cover. This operator also lets you combine multiple producers. Take a look at the following example:

    fun main(args: Array<String>) { 
      println("startWith Iterator") 
      Observable.range(5,10) 
        .startWith(listOf(1,2,3,4))//(1) 
        .subscribe { 
           println("Received $it") 
        } 
        println("startWith another source Producer") 
       Observable.range(5,10) 
         .startWith(Observable.just(1,2,3,4))//(2) 
         .subscribe { 
            println("Received $it") 
         } 
   } 

We can pass another source Observable or an Iterator instance to be prepended before the source Observable that the operator has subscribed to starts emitting.

In the preceding program, on comment (1), we used the startWith operator and passed an Interator instance to it. The startWith operator internally converts the passed Iterator instance to an Observable instance (it'll convert it to a Flowable instance in case you're using Flowable). Here is the signature of the startWith operator:

    fun startWith(items: Iterable<T>): Observable<T> { 
      return concatArray<T>(fromIterable<out T>(items), this) 
    } 

From the preceding signature of the startWith operator, we can also see that it uses concatArray internally, which we will be covering very soon in this chapter.

On comment (2), we used the startWith operator with another source Observable.

Here is the output of the program:

As we have got some grip on the startWith operator, now let's move forward with the zip operator. The zip operator implements a zipping mechanism to combine producers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.35.255