3
\$\begingroup\$

I'm developing an app that use socket to receive messages from a chat. I'm using an MVP approach and I store the data in a Singleton class named DataBridge like this:

class myApplication: Application() {

    val dataBridge: DataBridge = DataBridge()
    val deviceManager: DeviceManager = DeviceManager(this)

    override fun onCreate() {
        super.onCreate()
        instance = this

        //init Logger
        TimberImplementation.init()

        //init Maps
        Mapbox.getInstance(this, MAP_ACCESS_TOKEN)
    }

    companion object {
        lateinit var instance: InfiniteApplication
            private set
    }
}

I have the following scenario:

  • Main Activity: create socket connection and update data in DataBridge class. It has a ViewPagerAdapter with 4 fragments. Each Fragment has it's own Presenter.
  • Chat Activity: listen changes from DataBridge like onNewMessage (fired by HomeActivity) and display the chat

The question is: is a good practice to share Live Model by Application and make it accessible from presenter of different activities?

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review! Your code does seem to be a code stub, since there are likely relevant parts missing, so the results you get from the code review might be suboptimal. \$\endgroup\$
    – AlexV
    May 14, 2019 at 11:17

1 Answer 1

3
\$\begingroup\$

Is a good practice to share LiveData? Yeah

Here as you are using the data in databridge as a single source of truth and it is used hold data which is needed to be shared across multiple screen with live updates, Livedata is a really good option as it will also handle the lifecycle for you.

Android docs also has sample on Extending LiveData to create your own singleton data source which you may find helpful.

Also you can leverage the feature of Object declarations in kotlin to lazy initialize your DataBridge rather than in Application class.

\$\endgroup\$
1
  • \$\begingroup\$ Can you give some other example of Extending LiveData or can you tell what code should be there in StockManager? Thanks \$\endgroup\$
    – Scientist
    Sep 24, 2020 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.