Guest User

Untitled

a guest
Sep 21st, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. /*
  2. getByteStream()
  3. .observeOn(AndroidSchedulers.mainThread())
  4. .subscribeOn(Schedulers.computation())
  5. .writeBytesToFile(getPath(), generateNewFileName())
  6. .subscribeBy(onError = renderError())
  7. .addTo(disposables)
  8. */
  9.  
  10. fun Flowable<ByteArray>.writeBytesToFile(filesDir: File, fileName: String): Flowable<ByteArray> {
  11. val resourceSupplier = FileOutputStreamSupplier(filesDir, fileName)
  12.  
  13. val sourceSupplier = Function<FileOutputStream, Flowable<ByteArray>> { fileOs ->
  14. this@writeBytesToFile.doOnNext { byteArray ->
  15. fileOs.write(byteArray)
  16. }
  17. }
  18.  
  19. val disposer = Consumer<FileOutputStream> {
  20. it.flush()
  21. it.close()
  22. }
  23.  
  24. return Flowable.using(resourceSupplier, sourceSupplier, disposer)
  25. }
  26.  
  27. internal class FileOutputStreamSupplier(private val parent: File,
  28. private val fileName: String) : Callable<FileOutputStream> {
  29. override fun call(): FileOutputStream {
  30. parent.mkdirs()
  31. val file = File(parent, fileName)
  32. return FileOutputStream(file)
  33. }
  34. }
Add Comment
Please, Sign In to add comment