[英]How to make the map wait till the current index item is finished processing and then take the next item for processing using RxJava?
我正在嘗試將輸入流轉換為文件。 因此,當用戶選擇 1 張圖片時,一切正常。 但是當用戶選擇多個圖像時,例如 4 則下面的代碼無法按預期工作; 我在 Log 語句中只看到 2 個文件路徑。
compositeDisposable.add(Observable.fromIterable(inputStreamList)
.map {
FileUtils.saveInputStreamToFile(it, directory, 500)
}.toList()
.toObservable()
.subscribeOn(schedulerProvider.io())
.subscribe({
it.forEach {file->
Log.d("TAG", "Path ${file.path}")
}
Log.d("TAG", "Size ${it.size}")
}, {
})
)
這是 saveInputStreamToFile 方法
fun saveInputStreamToFile(input: InputStream, directory: File, height: Int): File? {
val currentTime = dateFormat.format(Date())
val imageName = "_$currentTime"
val temp = File(directory.path + File.separator + "flab\$file\$for\$processing")
try {
val final = File(directory.path + File.separator + imageName + ".$IMAGE_JPG")
val output = FileOutputStream(temp)
try {
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int = input.read(buffer)
while (read != -1) {
output.write(buffer, 0, read)
read = input.read(buffer)
}
output.flush()
saveBitmap(decodeFile(temp, height)!!, final.path, IMAGE_JPG, 80)
return final
} finally {
output.close()
temp.delete()
}
} finally {
input.close()
}
}
我希望僅在當前輸入 stream 轉換為文件后才采用下一個輸入 stream 。 如何做到這一點? 請幫忙
在 RX 中,您可以執行以下操作:
Observable.fromCallable {
return inputStreamList.map {
FileUtils.saveInputStreamToFile(it, directory, 500)
}.toList()
}.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Observer<List<File>> {
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(files: List<File>) {
//here you can iterate and complete do your work
files.forEach { file ->
Log.d("TAG", "Path ${file.path}")
}
Log.d("TAG", "Size ${files.size}")
}
override fun onError(e: Throwable) {
}
})
這將確保您的工作將在后台同步完成,並且您將按照指定在 MainThread 上的onNext()
中觀察您的結果。
確保您使用 package io.reactivex
編輯:
擺脫您的 RX package 並將這些設置在build.gradle
implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.