Skip to content

Completable Operator

Devrath edited this page Dec 28, 2023 · 1 revision

What is Completable Observable

  • A Completable Observable can emit only one event, A onComplete or an onError.

  • onComplete will not receive the result.

  • code

private val completableDemoSubscriptions = CompositeDisposable()

    private val completableObservable = Completable.create { emitter ->
        val fileName = "demo.txt"

        // Here we perform a reading of file
        try {
            // Open the file in the assets folder
            val inputStream = context.assets.open(fileName)

            // Read the file into a ByteArray
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.read(buffer)
            inputStream.close()

            val result = String(buffer, Charsets.UTF_8)

            // Send the success
            emitter.onComplete()
        } catch (e: Exception) {
            // Send the error
            emitter.onError(e)
        }
    }

    fun initiateCompletableObservableDemo() {
        completableObservable.subscribeBy (
            onError = {
                println("ErrorMessage-> ${it.localizedMessage}")
            },
            onComplete = {
                println("Completed")
            }
        ).addTo(completableDemoSubscriptions)
    }
  • Output Completed
Clone this wiki locally