Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object Utils {
- fun downloadFile(url:String, file:File) : Observable<Int>{
- return PublishSubject.create<Int> {
- val client = OkHttpClient()
- val request = Request.Builder()
- .url(url)
- .build()
- client.newCall(request).enqueue(object : Callback {
- override fun onFailure(call: Call, e: IOException) {
- e.printStackTrace()
- }
- @Throws(IOException::class)
- override fun onResponse(call: Call, response: Response) {
- if (!response.isSuccessful) throw IOException("Unexpected code $response")
- val inStream = response.body()?.byteStream()
- val bis= BufferedInputStream(inStream)
- val maxSize=response.body()?.contentLength()
- val stepSize= maxSize?.div(100)
- var currentValue=0
- var procent=0
- val bytes=ByteArray(2048)
- val fos = FileOutputStream(file)
- while (true) {
- val byteCount = bis.read(bytes)
- if (byteCount==-1) break
- fos.write(bytes, 0, byteCount)
- currentValue+=byteCount
- if (currentValue>= stepSize!!){
- procent++
- it.onNext(procent)
- currentValue=0
- }
- }
- fos.close()
- }
- })
- }
- }
- }
- fun downloadAudio(url:String, fileExternal: File){
- viewState.showLoading()
- Observable.fromCallable {
- val array=url.split("/")
- var nameFile=array[array.size-1]
- nameFile=nameFile.substring(0,nameFile.indexOf("?"))
- val file= File(fileExternal, nameFile)
- val link=""
- Thread.sleep(4000)
- Utils.downloadFile(link, file)
- }
- .doOnNext {
- Log.e("SearchAudioPresenter", "downloadAudio= ASD")
- }
- .subscribeOn(Schedulers.io())
- .observeOn(AndroidSchedulers.mainThread())
- .doFinally { viewState.hideLoading() }
- .subscribe({
- viewState.loadingSuccess()
- }, Throwable::printStackTrace).isDisposed
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement