由于我对RxJava / RxAndroid的经验不足,因此我尝试实现某些功能,但不确定如何执行。.我面临的问题是,此操作阻塞了我的UI线程..
首先,我正在初始化DataOutputStream和一个将读取内容并将其写入的类:
public static void startReceiveLogs() {
mReadFlag = true;
try {
os = new DataOutputStream(new FileOutputStream("/sdcard/myApp/" + TimeUtils.getCurrentTime(TimeZone.getDefault()) + "_logs.uedl"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
rxLogsReaderClass = new RxLogsReaderClass();
rxLogsReaderClass.startListening();
}
这是课程:
static class RxLogsReaderClass {
byte[] rbuf = new byte[64];
public void startListening() {
ExecutorService executor = Executors.newFixedThreadPool(2);
Observable<Integer> myObs = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(mSerial.read(rbuf, mSerialPortLog));
emitter.onComplete();
}
});
Observer<Integer> observer = new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
while (mReadFlag) {
try {
int len = mSerial.readLog(rbuf, mSerialPortLog);
if (len > 0) {
os.write(rbuf, 0, len);
}
} catch (NullPointerException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
};
myObs.subscribeOn(Schedulers.io());
myObs.observeOn(Schedulers.from(executor));
myObs.subscribe(observer);
}
}
这是一个读取方法,应该调用onNext()...它只是从USBDeviceConnection中读取内容并返回int:
public int readLog(byte[] buf, int channel) {
if (DeviceisXR2280X == 1) {
channel = 0;
}
int returnValue;
try {
returnValue = this.mDeviceConnection.bulkTransfer(this.mEXAREndpointIN[channel], buf, buf.length, 10000);
} catch (ArrayIndexOutOfBoundsException aioue) {
returnValue = this.mDeviceConnection.bulkTransfer(this.mEXAREndpointIN[this.mEXAREndpointIN.length - 1], buf, buf.length, 10000);
}
return returnValue;
}
我尝试在AndroidSchedulers.mainThread()和此线程上进行观察,但是在每种情况下,它都会阻塞主线程...您能告诉我我在做什么错吗。.