Search code examples
javaandroidandroid-mvp

Android MVP Where should i have a TextWatcher


I currently have my TextWatchers implemented on my view file (activity.java). However should they be in the presenter, since the presenter is the one who decided what to do after a user input, or is it wise to keep them where they are?


Solution

  • There are two sides to your problem:

    • on one hand the the TextWatcher is definitely part of the Android UI and since the Presenter should not know anything about Android specific code the Watcher should be part of the view
    • on the other hand the TextWatcher needs to handle the incoming events and apply business logic to it, and since the View should be es dumb as possible the Watcher should be part of the Presenter

    To fix this problem, my suggestion would be to keep the Watcher in the View, but only redirect it's incoming events to the Presenter:

    class TextWatcher(presenter: MVPWatcherInterface) : ParentTextWatcher {
    
      private val presenterInterface: WeakReference<MVPWatcherInterface> = WeakReference(presenter)
    
      override fun onSomeTextEvent(){
        presenterInterface.get()?.onWatcherEventSomeTextEvent()
      }
    }
    

    To implement this, you have to define MVPWatcherInterface and implement it in your Presenter and pass it to the TextWatcher when you create it in the View. This allows you to handle all your business logic inside onWatcherEventSomeTextEvent inside your Presenter.

    That way the code is clean and separated according to MVP rules :)

    (as a side note: the watcher I proposed uses a WeakReference to keep the MVPWatcherInterface -> I would highly recommend to implement it that way, so that your code won't generate any leaks by preventing the Presenter from being garbage collected)