0

I'v got this method from here and it works well:

@Throws(IOException::class)
fun readTextFromUri(ctx: Context, uri: Uri): String {
    val stringBuilder = StringBuilder()
    ctx.contentResolver.openInputStream(uri)?.use { inputStream ->
        BufferedReader(InputStreamReader(inputStream)).use { reader ->
            var line: String? = reader.readLine()
            while (line != null) {
                stringBuilder.append("$line\n")
                line = reader.readLine()
            }
        }
    }
    return stringBuilder.toString()
}

Then converted it to this method that returns each line using Observable:

fun getUriAsStringObservable(ctx: Context, uri: Uri): Observable<String> {
    return Observable.create {
        try {
            ctx.contentResolver.openInputStream(uri)?.use { inputStream ->
                BufferedReader(InputStreamReader(inputStream)).use { reader ->
                    var line: String? = reader.readLine()
                    while (line != null) {
                        it.onNext(line)
                        line = reader.readLine()
                    }
                    it.onComplete()
                }
            }
        } catch (e: IOException) {
            it.onError(e)
        }
    }
}

But it didn't work as I expected, after subscribing to it nothing is printed:

getUriAsStringObservable(this, uri)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .doOnNext {
        print("Next: $it")
    }
    .doOnError {
        print("Error: $it")
    }
    .doOnComplete {
        print("completed")
    }
    .subscribe()

What is my mistake?

RuNo280
  • 573
  • 4
  • 27

1 Answers1

0

I found three way to solve my issue:

1) Use Thread.sleep(1) after emitting each item.

2) Use custom scheduler which has non deamon thread link.

3) Use Flowable with BackpressureStrategy.BUFFER instead of Observable (Best way).

Flowable.create({
    try {
        ctx.contentResolver.openInputStream(uri)?.use { inputStream ->
            BufferedReader(InputStreamReader(inputStream)).use { reader ->
                var line: String? = reader.readLine()
                while (line != null) {
                    it.onNext(line)
                    line = reader.readLine()
                }
                it.onComplete()
            }
        }
    } catch (e: IOException) {
        it.onError(e)
    }
}, BackpressureStrategy.BUFFER)

Thank you Javid

RuNo280
  • 573
  • 4
  • 27