Cancellation

Instances of the Activity or Fragment class have life cycles that are represented by methods, such as onCreate and onDestroy. We should clean all resources by using the onDestroy method, in order to avoid memory leaks.

The subscribe method returns an instance of the Disposable type, as follows:

public final Disposable subscribe(Consumer<? super T> consumer) {
Objects.requireNonNull(consumer, "consumer");
return subscribe(consumer, null, null);
}

The Disposable interface contains two methods, as follows:

  • dispose cancels a publisher
  • isDisposed returns true if a publisher has already been cancelled

The following example code shows how to cancel a publisher when the onDestroy method is invoked:

class ObserverActivity : AppCompatActivity() {

private var disposable: Disposable? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_observer)
disposable = Flux.from<Unit> { subscriber ->
findViewById<Button>(R.id.button).setOnClickListener {
subscriber.onNext(Unit)
}
}.subscribe {
Toast.makeText(this, "Clicked!", Toast.LENGTH_LONG).show()
}
}

override fun onDestroy() {
super.onDestroy()
disposable?.dispose()
}
}

As you can see, the onDestroy method invokes the dispose method to unsubscribe from an instance of the Flux class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.206.25