rxjava2.1.5:在Android中将rxjava2与udpsocket一起使用,ObservableOnSubscribe订阅不调用

时间:2019-03-18 06:32:01

标签: android sockets rx-java2

我不想将udp套接字与rxjava2一起使用,以下是主要代码。

public void receive(int port, int timeout) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {

                try {

                    if (mSocket == null) {
                        mSocket = new DatagramSocket(null);
                        mSocket.setSoTimeout(timeout);
                        mSocket.setBroadcast(true);
                        mSocket.setReuseAddress(true);
                        mSocket.bind(new InetSocketAddress(port));
                    }

                    while (!mIsClosed) {
                        //接收数据的buf数组并指定大小
                        byte[] buf = new byte[1024];
                        //创建接收数据包,存储在buf中
                        DatagramPacket packet = new DatagramPacket(buf, buf.length);
                        multicastLock.acquire();

                        //接收操作
                        mSocket.receive(packet);
                        byte data[] = packet.getData();// 接收的数据

                        String result = new String(data);

                        //检查数据是否合法
                        if (checkMessageLegal(result)) {
                            emitter.onNext(result);
                        } else {
                            emitter.onError(new Exception("the data is illegal"));
                        }
                    }

                } catch (SocketException e) {
                    LogUtils.w(TAG, e.getMessage());
                    if (!mIsClosed) {
                        emitter.onError(e);
                    }
                } catch (IOException e) {
                    LogUtils.w(TAG, e.getMessage());
                    if (!mIsClosed) {
                        emitter.onError(e);
                    }
                }

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                  mDisposable = d;
            }

            @Override
            public void onNext(String result) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

当后向活动调用mSocket.close()和mDisposable.dispose()时,我在活动的onCreate()中调用receive(...)。但是,当我多次致电receive(...)时,有时无法执行subscribe()。我是Rx world的新手,可以使用一些帮助来找出问题所在。预先感谢!

0 个答案:

没有答案