如何处理RxJava中的所有5个线程

时间:2019-02-11 15:08:34

标签: android kotlin rx-java rx-java2 rx-android

我有一个简单的Kotlin类,它具有一个“惰性”属性。我模拟此属性从网络获取用户名并返回Observable。

之后,我尝试检索此属性,例如5次并收到意外结果。

这是示例类(Kotlin)的源代码:

class LazyInitialization {

    private val username by lazy {
        println("lazy init started")
        Thread.sleep(2000)
        println("lazy init finished")
        Observable.just("username")
    }


    fun print(number: Int) {
        println("Print started [$number]")
        username.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
            println("Return preference: [$it]")
        }
    }
}

这是我如何称呼它(Java)的示例:

LazyInitialization lazyInitialization = new LazyInitialization();
for (int i = 0; i < 5; i++) {
    lazyInitialization.print(i);
}

输出为:

I/System.out: Print started [0]
I/System.out: lazy init started
I/System.out: lazy init finished
I/System.out: Print started [1]
I/System.out: Print started [2]
I/System.out: Print started [3]
I/System.out: Print started [4]
I/System.out: Return preference: [username]
I/System.out: Return preference: [username]

如您所见,偏好设置返回了两次,但应返回值5次。

还有另一个奇怪的时刻,那就是如果我提高输出(增加数字打印)

println("Return preference: [$number] [$it]")

所以print()方法看起来像这样:

fun print(number: Int) {
        println("Print started [$number]")
        username.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
            println("Return preference: [$number] [$it]")
    }
}

然后我得到了预期的结果:

I/System.out: Print started [0]
I/System.out: lazy init started
I/System.out: lazy init finished
I/System.out: Print started [1]
I/System.out: Print started [2]
I/System.out: Print started [3]
I/System.out: Print started [4]
I/System.out: Return preference: [0] [username]
I/System.out: Return preference: [1] [username]
I/System.out: Return preference: [2] [username]
I/System.out: Return preference: [3] [username]
I/System.out: Return preference: [4] [username]

我也不明白它发生的原因。

有人对此行为有任何想法吗?

0 个答案:

没有答案