Last active
February 20, 2020 23:02
-
-
Save patrickcousins/a01f4b28bad0b5936159b20e6134a44a to your computer and use it in GitHub Desktop.
ideas around a fake mini job queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.android.lib.rx | |
import io.reactivex.Observable | |
import java.util.concurrent.ConcurrentLinkedDeque | |
import java.util.concurrent.TimeUnit | |
class JobExample { | |
val queue = ConcurrentLinkedDeque<Item>() | |
fun add(item: Item): Observable<Item>? { | |
queue.addLast(item) | |
//queue.removeIf { it.key == item.key } //something like this logic to cancel waiting jobs of the same 'key' | |
return Observable | |
.fromCallable { | |
val next = queue.pollFirst() | |
next?.let { //fake network call | |
println("making fake network call for ${next.key} queue size ${queue.size}") | |
Thread.sleep(2000) | |
} | |
item //end fake network call | |
} | |
.repeatWhen { repeater -> | |
if (queue.isEmpty()) { | |
Observable.empty<Item>() | |
} else { | |
println("delay...queue size: ${queue.size}") | |
repeater.concatMap { Observable.timer(150, TimeUnit.MILLISECONDS) } | |
} | |
} | |
} | |
} | |
data class Item(val key: String, val value: Boolean) | |
/////// test | |
@Test | |
fun jobtest() { | |
val jobex = JobExample() | |
val list = mutableListOf<Item>() | |
for (i in 0..10) { | |
list.add(Item("key $i", true)) | |
} | |
//simulate being clogged up! | |
val preloadedKeys = mutableListOf<Item>() | |
for (i in 0..10) { | |
preloadedKeys.add(Item("preloaded key $i", true)) | |
} | |
jobex.queue.addAll(preloadedKeys) | |
list.forEach { | |
jobex.add(it)?.subscribe() | |
} | |
println("done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment