How to use RxJava combineLatest operator with more than 9 observables

前端 未结 6 598
一个人的身影
一个人的身影 2020-12-16 17:25

I\'m using RxJava and I want to combine 12 different observables using the operator combineLatest.

I saw a function prototype that takes a list of obse

6条回答
  •  醉酒成梦
    2020-12-16 17:35

    RxKotlin supports upto 9 opertators in parameters in combineLatest() method but to use more than 9 parameters means to pass unlimited dynamic custom object arraylist you can use it as below:

    First Let me give you simple example with only two parameters with custom data types

    val name = Observable.just("MyName")
    val age = Observable.just(25)
    Observables.combineLatest(name, age) { n, a -> "$n - age:${a}" }
                    .subscribe({
                        Log.d("combineLatest", "onNext - ${it}")
                    })
    

    Now what if i want to pass multiple parameters in combineLatest? Then your answer is below: (i have used custom data types, so someone's custom problem can also be solved here)

    val myList = arrayOf(Observable.just("MyName"),
                    Observable.just(2),
                    Observable.just(3.55),
                    Observable.just("My Another String"),
                    Observable.just(5),
                    Observable.just(6),
                    Observable.just(7),
                    Observable.just(8),
                    Observable.just(9),
                    Observable.just(10),
                    Observable.just(11),
                    Observable.just(12),
                    Observable.just(13),
                    Observable.just(14),
                    Observable.just(15))
    
    Observable.combineLatest(myList, {
        val a = it[0] as String
        val b = it[1] as Int
        val c = it[2] as Float
        val d = it[3] as String
        val e = it[4] as Int
        val f = it[5] as Int
        val g = it[6] as Int
        val h = it[7] as Int
        val i = it[8] as Int
        val j = it[9] as Int
        val k = it[10] as Int
        val l = it[11] as Int
        val m = it[12] as Int
        "$a - age:${b}" })
            .subscribe({
                Log.d("combineLatest", "onNext - ${it}")
            })
    

提交回复
热议问题