我有一个现有的Java代码,我想用RxJava编写它。我正在尝试用定制的模式来振动一个装置。
自定义模式为{onTime1,offTime1,onTime2,offTime2...}格式,其中,设备在onTime毫秒内振动,并在下一次振动之前等待offTime。
以下是我的Java代码:
for (int i = 0; i < customPattern.length - 1; i++) {
try {
io.writeCharacteristic(Profile.UUID_SERVICE_VIBRATION, Profile.UUID_CHAR_VIBRATION, this.getProtocol());
Thread.sleep(customPattern[i]);
io.writeCharacteristic(Profile.UUID_SERVICE_VIBRATION, Profile.UUID_CHAR_VIBRATION, Protocol.STOP_VIBRATION);
Thread.sleep(customPattern[i + 1]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}编辑--到目前为止,我已经以如下方式实现了它,并且它的工作方式与预期的一样。是否有一个更优化的解决方案:我让将数组拆分为元组2 (onTime,offTime),然后发出它们,然后在Schedulers.computation()线程上执行所有操作
Observable.fromIterable(tuple).observeOn(Schedulers.io()).subscribeOn(Schedulers.computation()).subscribe(
t->{
//onNext Method
bluetoothIo.writeCharacteristic(Profile.UUID_SERVICE_VIBRATION, Profile.UUID_CHAR_VIBRATION, Protocol.VIBRATION_WITH_LED);
Thread.sleep(t[0]);
bluetoothIo.writeCharacteristic(Profile.UUID_SERVICE_VIBRATION, Profile.UUID_CHAR_VIBRATION, Protocol.STOP_VIBRATION);
Thread.sleep(t[1]);
},
e->e.printStackTrace(),
()->{//onComplete}
);因此,给定这个数组作为输入{10、20、30、40、50},我希望以以下方式执行
function1
wait(10)
function2
wait(20)
function1
wait(30)
function2
wait(40)
function1
wait(50)
function2发布于 2020-07-01 16:40:59
你可以这样做。
doOnNext(...)
您应该能够将其复制/粘贴到IDE中:
@Test
public void testVibrate()
{
// Delay pattern:
Flowable<Integer> pattern = Flowable.just(
500, // on
250, // off
500, // on
250, // off
1000, // on
0 ); // off
// Alternating true/false booleans:
Flowable<Boolean> onOff = pattern
.scan(
true, // first value
( prevOnOff, delay ) -> !prevOnOff ); // subsequent values
// Zip the two together
pattern.zipWith( onOff, ( delay, on ) -> Flowable.just( on )
.doOnNext( __ -> System.out.println( "vibrate: " + on )) // Invoke function based on value
.delay( delay, TimeUnit.MILLISECONDS )) // Delay the value downstream
.concatMap( on -> on ) // Concatenate the nested flowables
.ignoreElements()
.blockingAwait();
}https://stackoverflow.com/questions/62663812
复制相似问题