Skip to content

Single Operator

Devrath edited this page Dec 28, 2023 · 1 revision

What is Single Observable

A Single Observable can emit only one event, A onSuccess or a onError

  • code
    private val singleDemoSubscriptions = CompositeDisposable()

    private val singleObservable = Single.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)
        } catch (e: Exception) {
            // Send the error
            emitter.onError(e)
        }
    }

    fun initiateSingleObservableDemo() {
        singleObservable.subscribeBy (
            onSuccess = {
                println("Result-> $it")
            },
            onError = {
                println("ErrorMessage-> ${it.localizedMessage}")
            },
        ).addTo(singleDemoSubscriptions)
    }
  • Output You can see the content of the text file in the console
Clone this wiki locally