How to create infinite interval Observable that wi

2019-07-13 05:46发布

问题:

I am trying to create an Observable that will emit new object every second. So for now i am just zipping one Observable, which emits finite number of objects from a list, with interval Observable.

   val list1 = mutableListOf<SomeClass1>(
            SomeClass1("1", 1), SomeClass1("2", 2), SomeClass1("3", 3),
            SomeClass1("4", 4), SomeClass1("5", 5), SomeClass1("6", 6),
            SomeClass1("7", 7), SomeClass1("8", 8), SomeClass1("9", 9)
    )

    val someClass1Observable = Observable
            .fromIterable(list1)
            .zipWith(Observable.interval(2, TimeUnit.SECONDS),
                    BiFunction { item: SomeClass1, _: Long -> item })

So how to actually make this infinite, in a way that every 2 second there will be emiited new object of class SomeClass1 with some parameters?

回答1:

Here is the answer for my question, that satisfies my:

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var counter = 0

    val periodicSomeClass1 = Observable.interval(1, TimeUnit.SECONDS)
            .flatMap(
                    {
                        counter++
                        Observable.just(SomeClass1("$counter", counter))
                    }
            )


    periodicSomeClass1.subscribe { t: SomeClass1 -> Log.v("periodicSomeClass1", t.toString())  }

}