Skip to content

Filter Operators : Filter

Devrath edited this page Dec 29, 2023 · 1 revision

1_Uaiw2DzhmlDwXOpYXUfmyg

What is the filter operator ?

  • This operator helps you to receive only the onNext emission of an element that satisfies the predicate condition that we specify.
  • It ignores all the other onNext elements.
  • It also allows onError and onComplete emissions.

Code

    // Create the observable
    private val filterSubject = PublishSubject.create<String>()

    // Create the subscriber
    private fun subscribeFilterAt(){
        filterSubject.filter { it==episodeII }.subscribeBy(
            onNext = { println("Element printed:-> $it") },
            onError = { println("Error Triggered") },
            onComplete = { println("Complete Triggered") }
        )
    }

    fun filterDemo() {
        // Subscribe the observer to the observable
        subscribeFilterAt()
        // Publish some elements
        filterSubject.onNext(episodeI)
        filterSubject.onNext(episodeII)
        filterSubject.onNext(episodeIII)
        // Indicate completion of stream
        filterSubject.onComplete()
    }

Output

Attack of the Clones
Complete Triggered
Clone this wiki locally