Open In App

Understanding RxJava Zip Operator With Example

Improve
Improve
Like Article
Like
Save
Share
Report

According to the official RxJava documentation “Zip combines the emissions of several Observables using a given function and emits single items based on the outcomes of this function for each combination”. The zip operator enables us to obtain results from several observables at the same time.

Image 1. Understanding the Zip Structure.

Assume we have the following two network observables: GfGCoursesData – A network observable that yields a list of courses offered at Geeks for Geeks. GfGDSA – A network observable that returns a list of Geeks for Geeks Data Structure Courses

GfFCourses have noticed the following:

Kotlin




fun getGfGCoursesData(): Observable<List<User>> {
    return networkService.getGfGCoursesData()
}


GFGDSA is as follows:

Kotlin




fun getGFGDSA(): Observable<List<User>> {
    return networkService.getGFGDSA()
}


And here is our NetworkService:

Kotlin




class NetworkService {
      
    fun gfgCourses(): Observable<List<User>> {
        return Observable.create<List<User>> { shooterData ->
            if (!shooterData.isDisposed) {
                // fetch gfgData from network
                val gfgData = fetchUserListFromNetwork()
                shooterData.onNext(gfgData)
                shooterData.onComplete()
            }
        }.subscribeOn(Schedulers.io())
    }
  
    fun gfgDSA(): Observable<List<User>> {
        return Observable.create<List<User>> { shooterData ->
            if (!shooterData.isDisposed) {
                // fetch gfgData from network
                val gfgData = fetchUserListFromNetwork()
                shooterData.onNext(gfgData)
                shooterData.onComplete()
            }
        }.subscribeOn(Schedulers.io())
    }
  
    private fun fetchUserListFromNetwork(): List<User> {
        return listOf()
    }
  
}


As an example, consider the following observer:

Kotlin




private fun getTheObserver(): Observer<List<User>> {
    return object : Observer<List<User>> {
        override fun gfgSubscribed(d: Disposable) {
            println("gfgSubscribed")
        }
  
        override fun onNext(userList: List<User>) {
            println("onNext : $userList")
        }
  
        override fun onError(e: Throwable) {
            println("onError : ${e.message}")
        }
  
        override fun onComplete() {
            println("onComplete")
        }
    }
}


A utility tool for identifying courses that are in common.

Kotlin




private fun CommonCourses(GfGCourses: List<User>,
                                   gfgDSACourses: List<User>): List<User> {
    val CommonCourses = ArrayList<User>()
    for (gfgDSACourse in gfgDSACourses) {
        if (GfGCourses.contains(gfgDSACourse)) {
            CommonCourses.add(gfgDSACourse)
        }
    }
    return CommonCourses
}


Let’s put it all together to obtain a better understanding of the zip operator.

Kotlin




Observable.zip(
    gfgCourses(),
    gfgDSACourses(),
    BiFunction<List<User>, List<User>, List<User>> { cricketFans, gfgCourses->
        // fetching results at once.
        return@BiFunction filterUserWhoLovesBoth(cricketFans, gfgDSA)
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(getObserver())


Summary

First, we make two network requests (simultaneously because we’re using Zip Operator), and then we select the courses of DSA which are part of the main courses. Both network calls are executed in parallel by zipping two observables with the RxJava Zip operator. When both observables have finished, we obtain the outcome of both. We obtain the outcomes of both observables at the same time in this manner.

Conclusion with some Advantages of RxZip

  • Run all jobs in parallel if Schedulers are appropriately assigned to each observable.
  • When all of the jobs have been finished, return the results of all of them in a single callback.
  • We may utilize the RxJava Zip Operator to solve the intriguing problem this way.


Last Updated : 25 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads