如何让地图等待当前索引项处理完毕,然后使用RxJava处理下一个项



我正在尝试将输入流转换到文件中。所以当用户选择一张图片时,一切都很好。但当用户选择多个图像时,例如4,则下面的代码没有按预期工作;我在Log语句中只看到两个文件路径。


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()
}
}

我希望下一个输入流只在当前输入流转换为文件后才被获取。如何做到这一点?请帮助

在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()中观察结果。

确保使用包io.reactivex

编辑:

去掉你的RX包,并将其设置在build.gradle

implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'

相关内容

最新更新