Sobes.tech
Junior — Middle

What methods can be used to implement cancellation of requests related to Presenter in the MVP pattern for interaction with the View?

sobes.tech AI

Answer from AI

To cancel requests in Presenter when using the MVP pattern, several approaches can be applied:

  1. Cancellation via Disposable (RxJava) — if requests are implemented using RxJava, you can store the Disposable and call dispose() when destroying the Presenter or View.

  2. Using CoroutineScope and Job (Kotlin Coroutines) — if requests are executed through coroutines, you can cancel the associated Job when destroying the Presenter.

  3. Cancellation via Callbacks or Future — if a standard asynchronous call mechanism is used, you can implement a cancellation flag and check it before processing the result.

  4. Cancellation of network requests — if requests are made through OkHttp or Retrofit, you can call cancel() on the corresponding Call.

Example with RxJava:

class MyPresenter {
    private var disposable: Disposable? = null

    fun loadData() {
        disposable = api.getData()
            .subscribe({ data -> view.showData(data) }, { error -> view.showError(error) })
    }

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