Search code examples
androidandroid-custom-view

Is it a good idea to add a WebService Request inside a Custom View?


So I have lets say I have a requirement where whenever the specific button is pressed, I should call a webservice to send some logs.

This button is present for multiple screens, so I though why not place it inside a CustomView View and call the webservice from there?

Then I'll just add this custom view to the xml layout and I don't have to worry about a thing anymore. Is it a good idea?

If it's not can someone suggest a better solution? Thanks.


Solution

  • As for your existing architecture (MVP), it is better to put the logic in the Presenter, actually there should not be any logic on the View (in your case, custom view) aside from taking input (eg: click of a button), and providing output.

    Assuming you set a click listener on your button (well of course):

    button.setOnClickListener { yourPresenter.doSomeAction() }
    

    and in YourPresenter:

    fun doSomeAction() {
       //do necessary action for the button
       //after that, send logs
    }
    

    Following these pattern, you can easily make unit tests on your presenter like test if the logs is actually called, (you can also specify exact input).

    Note: If you're using Clean Architecture, I recommend to put it on the domain layer (Interactor/UseCase) as Presentation Layer doesn't care what and when to log.