Skip to content

Combining Operators : Zip

Devrath edited this page Dec 29, 2023 · 1 revision

1_oY4pB5RbNeloyauM1tpWmg

What is the Zip operator ?

  • The zip operator in RxKotlin is used to combine the emissions of multiple Observables in a pairwise manner.
  • It takes items emitted by each Observable and combines them into a single item using a provided function, then emits the result.

Code

    private val observableZip1 = Observable.just(1, 2, 3)
    private val observableZip2 = Observable.just("Red", "Green", "Blue")

    // Combining the two Observables using the zip operator
    private val zippedObservable = Observable.zip(
        observableZip1,
        observableZip2
    ) { number, color -> "Number: $number, Color: $color" }

    fun zip() {
        // Subscribing to the zipped Observable
        zippedObservable.subscribeBy(
            onNext = { result -> println("Received: $result") },
            onError = { error -> println("Error: $error") },
            onComplete = { println("Zip completed") }
        )
    }

Output

Received: Number: 1, Color: Red
Received: Number: 2, Color: Green
Received: Number: 3, Color: Blue
Zip completed
Clone this wiki locally