Home > Software design >  How to init, refresh fragment when notification comes?
How to init, refresh fragment when notification comes?

Time:12-14

Is it possible to handle events like when notification appears the action like auto refreshing, initmethod in Fragment. I have workmanager implemented I could do it using sharepreferences, but it is not instant and user has to refresh it by himself. I made a little research and there is kotlin channels, do they works instantly, automatically iwthout user action?

CodePudding user response:

Using LiveData

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

CodePudding user response:

There are multiple options, the common way is to send broadcast like this :

val intent = Intent("YOUR_ACTION")
intent.putExtra("key","value")
sendBroadcast(intent)

from your MessagingService (such as FirebaseMessagingService), then register broadcast in your fragment (preferably in onViewCreated() ), don't remember to unregister your broadcast.

the other option is using LiveData or other observer pattern libraries like RxJava. in this case you have to define your observable object in your service class then observe it from your fragment.

Note that if using RxJava you have to take care of disposing the observeable. LiveData is a lifecycle aware component so you don't need to worry about the memory leak or emitting while fragment is not available.

  • Related