publishSubject的onNext方法正在连续调用(在不均匀的时间中,大约在1毫秒内) 并且要求每1秒钟发出一次这些项目,并且数据不应该丢失意味着应该发射每个项目。
publishSubject.onNext("Data1");
publishSubject.onNext("Data2");
publishSubject.onNext("Data3");
publishSubject.onNext("Data4");
publishSubject.onNext("Data5");
publishSubject.onNext("Data6");
publishSubject.onNext("Data7");
,依此类推... 请参阅代码结构以供参考:
var publishSubject = PublishSubject.create<String>()
publishSubject.onNext(stateObject) // Executing at every milliseconds...
publishSubject
/* Business Logic Required Here ?? */
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
// Should execute at every 1 second
}
请帮助,在此先感谢
答案 0 :(得分:1)
如何将物品存储在双端队列中。然后,使用协程启动挂起功能来每秒获取双端队列的第一个元素?
这里有一些又脏又的代码只是为了确保它能正常工作。 您可以在kotlin website上在线运行此代码。 请记住,我是Kotlin的新手。
val deque: Deque<String> = ArrayDeque()
var refMillisAdd: Long = 0
var refMillisTake: Long = 0
fun main() {
println(" Delay(ms) -> Action")
println("---------------------")
kotlinx.coroutines.runBlocking {
launch {
refMillisAdd = currentTimeMillis()
refMillisTake = currentTimeMillis()
for(i in 0..20){
oncePer10ms(i.toString())
refMillisAdd = currentTimeMillis()
}
for(i in 0..6){
oncePerSecond()
refMillisTake = currentTimeMillis()
}
}
}
}
suspend fun oncePerSecond(){
kotlinx.coroutines.delay(1_000L)
println(" ${currentTimeMillis() - refMillisTake} -> TAKE ${deque.pop()}")
}
suspend fun oncePer10ms(item: String){
kotlinx.coroutines.delay(10L)
deque.add(item)
println(" ${currentTimeMillis() - refMillisAdd} -> ADD $item")
}
上面的代码打印:
Delay(ms) -> Action
---------------------
17 -> ADD 0
11 -> ADD 1
10 -> ADD 2
10 -> ADD 3
10 -> ADD 4
10 -> ADD 5
10 -> ADD 6
10 -> ADD 7
10 -> ADD 8
11 -> ADD 9
10 -> ADD 10
10 -> ADD 11
10 -> ADD 12
11 -> ADD 13
10 -> ADD 14
10 -> ADD 15
11 -> ADD 16
10 -> ADD 17
10 -> ADD 18
10 -> ADD 19
11 -> ADD 20
1223 -> TAKE 0
1000 -> TAKE 1
1000 -> TAKE 2
1001 -> TAKE 3
1000 -> TAKE 4
1000 -> TAKE 5
1000 -> TAKE 6
答案 1 :(得分:1)
此Observable
类的功能扩展正是您需要的:
fun <T> Observable<T>.delayBetweenItems(timeout: Long, unit: TimeUnit): Observable<T> =
Observable.zip(this, Observable.interval(timeout, unit), BiFunction<T, Long, T> { item, _ -> item })
您可以在项目的某些实用工具类中对其进行声明,然后像其他 RxJava 运算符一样应用它:
publishSubject
.delayBetweenItems(1000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
// Should execute at every 1 second
}