Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand Observable.fromArray in RxJava

I am trying to learn different operators of RxJava. I was a little confused between Observable.just and Observable.fromArray() and how they emit Observables.

Individual integers works fine, but to understand the difference better, I am trying to use arrays. I have below code which works fine for individual integers , but when I pass array, it says some compilation error and I cannot understand how to resolve.

Code for Individual Integers

Observable.fromArray(10,20,30).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                Util.d("Emit Integers : "+ it)
            })

The Output is :

Emit Integers : 10
Emit Integers : 20
Emit Integers : 30

Now to emit integers from some list I try below code:

var numbers = arrayOf<Int>(1, 2, 3)
Observable.fromArray(numbers).subscribeOn(Schedulers.io())
       .observeOn(AndroidSchedulers.mainThread())
        .subscribe({
            Util.d("Emit Integers: "+ it)
         })

The Output I get is

Emit Integers: [Ljava.lang.Integer;@8a69c02

What I expect is to return each item of array as Observable. Is it not possible with fromArray() ? If not, What is the use of Observable.fromArray()

like image 671
kukroid Avatar asked Nov 16 '25 08:11

kukroid


2 Answers

According to their doc fromArray() only supports reference arrays. But in kotlin arrayOf<Int>() returns Array object. If we put a kotlin Array object in fromArray() method, it creates array of Array object (in java, it will be Array[]). So after subscription Observable returns that object of Array. But if we put items in fromArray() method, it will create array of Int. So after subscription it returns Int. If you want to iterate over any mutable iterable, then you can try Observable.fromIterable().

like image 189
shafayat hossain Avatar answered Nov 19 '25 09:11

shafayat hossain


        val arr = arrayOf("111", "222")

        Observable.fromArray(*arr)
            .subscribe {
                Log.d("test", "$it")
            }

        Observable.fromIterable(arr.asIterable())
            .subscribe {
                Log.d("test", "$it")
            }
like image 45
Gary Avatar answered Nov 19 '25 10:11

Gary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!