Skip to content

Maybe Operator

Devrath edited this page Dec 28, 2023 · 1 revision

What is Completable Observable

  • A Completable Observable can emit all three, A onComplete, or an onErroror onSuccess

  • But it can emit just one of these possible events and not a combination of these

  • code

private val maybeDemoSubscriptions = CompositeDisposable()

    private val maybeObservable = Maybe.create<String> { 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.onSuccess(result)
            // Send the complete event
            emitter.onComplete()
        } catch (e: Exception) {
            // Send the error
            emitter.onError(e)
        }
    }

    fun initiateMaybeObservableDemo() {
        maybeObservable.subscribeBy (
            onSuccess = {
                println("Result-> $it")
            },
            onError = {
                println("ErrorMessage-> ${it.localizedMessage}")
            },
            onComplete = {
                println("Completed")
            }
        ).addTo(maybeDemoSubscriptions)
    }
Clone this wiki locally