线程工作有些麻烦

时间:2018-02-25 10:20:48

标签: java android multithreading kotlin rx-java2

我的事件emmiter类有代码:

val udpObservable = Observable.create<Int> { emitter ->
        val listener = object : SocketListener() {
            override fun onUdpServerListenerCreated(inetAddress: InetAddress, port: Int) {
                emitter.onNext(port)
                emitter.onComplete()
            }

        }
        //add listener here
        socketSource.subscribe(listener)
        emitter.setCancellable { socketSource.unSubscribe(listener) }
    }.subscribeOn(Schedulers.io())
            .doOnNext { Log.d("123-thread", "current is: " + Thread.currentThread().name) }
            .onErrorReturn { throw ConnectionException(it) }
            .subscribe()

我试图克服Observable:

RxCachedThreadScheduler-1 thread

但是在测试期间,而不是我看到的预期 D/123-thread: current is:-> main 工作

const emptyCount = (a=='') + (b=='') + (c=='');
if (emptyCount > 0 && emptyCount != 3) {
    alert('Please fill all elements');
}

你能帮助我吗?请。我的错误在哪里?如何为rx链实现所需的RxCachedThreadScheduler线程?

1 个答案:

答案 0 :(得分:0)

创建Observable的代码将在调度程序上执行,任何地方都没有隐式的上下文更改。

您的事件来自主线程上的侦听器。然后将它们发送到同一线程上的发射器。

  

因此,订阅依赖于调度程序io Thread,但是发行者继续使用主线程

So, subscription go on io, but emitters go on main emitters go on main

因此解决方案是在Observable create之后添加observerOn(Schedulers.newThread())Like this

val udpObservable = Observable.create<Int> { emitter ->
        val listener = object : SocketListener() {
            override fun onUdpServerListenerCreated(inetAddress: InetAddress, port: Int) {
                emitter.onNext(port)
                emitter.onComplete()
            }

        }
        //add listener here
        socketSource.subscribe(listener)
        emitter.setCancellable { socketSource.unSubscribe(listener) }
    }.subscribeOn(Schedulers.io())

      //need add this for work with emmit data on background 
     .observerOn(Schedulers.newThread())
            .doOnNext { Log.d("123-thread", "current is: " + Thread.currentThread().name) }
            .onErrorReturn { throw ConnectionException(it) }
            .subscribe()