Michael Job
09/29/2022, 3:20 PMprivate val modelScope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)
fun loadImageBitmap(id: Int) {
if (currentId == id) {
return
}
currentId = id
modelScope.coroutineContext.cancelChildren().also { print(".") }
//cancel all requests before the current one - prints a dot each just for demonstrating
modelScope.launch { //Coroutine #1
delay(500) //simulate longer http request
println("\njob ${this.coroutineContext.job.hashCode()} gets Image $id")
currentImage = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
URL("$baseUrl$id-1.jpg").openStream()
}
.buffered()
.use(::loadImageBitmap) // loads image
}
}
Casey Brooks
09/29/2022, 3:26 PMJob
of whatever’s running and cancel that, rather than checking and cancelling children of the CoroutineScope
itself.
private var currentJob: Job? = null
private val modelScope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)
fun loadImageBitmap(id: Int) {
currentJob?.cancel()
currentJob = modelScope.launch {
// load the image
}
}
Michael Job
09/29/2022, 3:42 PMephemient
10/01/2022, 1:55 PMval requests = MutableSharedFlow(onBufferOverflow = DROP_OLDEST)
val job = modelScope.launch {
requests.collectLatest {
// load the image
}
}
fun startLoadingImage(request) {
requests.tryEmit(request)
}
otherwise you have to ensure thread safety around your job
manipulation somehowMichael Job
10/02/2022, 8:51 AMMichael Job
10/02/2022, 8:54 AMval requests = MutableSharedFlow(onBufferOverflow = BufferOverflow.DROP_OLDEST)
val job = modelScope.launch {
requests.collectLatest {
delay(500) //simulate longer http request
println("\njob ${this.coroutineContext.job.hashCode()} gets Image $id")
currentImage = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
URL("$baseUrl$id-1.jpg").openStream()
}
.buffered()
.use(::loadImageBitmap) // lädt die Bitmap vom Stream
}
}
fun startLoadingImage(request) {
requests.tryEmit(request)
}
this is most definatly not what you mean, as it does not even compile, what should the request be? sorry, got to look up SharedFlow docs first, I guess 😉