Menu
Who Do Is
  • Home
  • What
  • How
  • Is
  • Can
  • Are
  • Does
  • Do
  • Why
  • Who
  • Where
  • Which
  • Which
  • Should
  • Will
  • When
  • What’s
  • Did
Who Do Is

[ANSWERED] java – How to update server response in UI using MVVM pattern

Posted on November 14, 2022

Solution 1 :

To implement that you firstly need to create a class which has the status of the response ,
Loading which is before the fetching of the data and there you can set progress bar to visible then on success you would set the data to your adapter and right after your hide your progress bar and in the on failure one , you show the toast message error

  • This is the generic class
class AuthResource<T>(
    var authStatus : AuthStatus? = null,
    var data : T,
    var msg : String? = null

)

fun <T> success(@Nullable data: T): AuthResource<T> {
    return AuthResource(
        AuthStatus.Success,
        data,
        null
    )
}

fun <T> Error(@NonNull msg: String?, @Nullable data: T) : AuthResource<T>? {
    return AuthResource(
        AuthStatus.ERROR,
        data,
        msg
    )
}

fun <T> loading(@Nullable data: T): AuthResource<T>? {
    return AuthResource(
        AuthStatus.LOADING,
        data,
        null
    )
}


enum class AuthStatus {
    Success, ERROR, LOADING
}
  • This is my view model where i implement the authResource with the api response
class MainViewModel @Inject constructor( private var webAuth: WebAuth,
    private var favFoodDao: FavFoodDao,
    private var application: Application) : ViewModel() {

    /// you have to create MediatorLiveData with authresource which contains your modelclass 

    private var mediatorLiveData = MediatorLiveData<AuthResource<WrapLatestMeals>>()
    
    ///Here you return a livedata object 
    fun ObserverCountries(): LiveData<AuthResource<WrapCountries>> {
        var liveData = LiveDataReactiveStreams.fromPublisher(
            webAuth.getCountries()
                 ///onerrorreturn , rxjava operator which returns error in case 
                 ///of response failure 
                .onErrorReturn(object : Function<Throwable, WrapCountries> {
                    override fun apply(t: Throwable): WrapCountries {
                        var country = WrapCountries()
                        return country
                    }
                })
                .map(object : Function<WrapCountries, 
                     AuthResource<WrapCountries>> {
                    override fun apply(t: WrapCountries): 
                        AuthResource<WrapCountries> {
                        if(t.meals.isNullOrEmpty())
                        {
                            return Error(
                                "Error",
                                t
                            )!!
                        }
                        return success(t)
                    }
                })
                .subscribeOn(Schedulers.io())
        )

       
        //add that data to mediatorLivedata 
        mediatorLiveDataCountries.addSource(liveData, Observer {
            mediatorLiveDataCountries.postValue(it)
            mediatorLiveDataCountries.removeSource(liveData)
        })
        return mediatorLiveDataCountries

    }

  • This is how you handle the status in your MainActivity
 mainViewModel = ViewModelProvider(this,provider)[MainViewModel::class.java]
        mainViewModel.ObserverCountries().observe(viewLifecycleOwner, Observer {
             when(it.authStatus) {
                 AuthStatus.LOADING -> /// here you show progressbar in response pre-fetch
                 {
                     
                     countriesFragmentBinding.countryprogress.show()
                 }
                 AuthStatus.Success -> { // here you update your ui

                     countriesAdapter = CountriesAdapter(it.data.meals!!, 
                     requireContext())
                     countriesFragmentBinding.recyclercountries.adapter = countriesAdapter
                     countriesAdapter!!.deleteCategory(23)
                     countriesFragmentBinding.countryprogress.hide()
                 }
                 AuthStatus.ERROR -> // here you hide your progressbar and show your toast
                 {
                   
                     countriesFragmentBinding.countryprogress.hide()
                     ToastyError(requireContext(),getString(R.string.errorretreivingdata))
                 }

             }
        })

        return countriesFragmentBinding.root
    }

}

Problem :

I am using MVVM pattern in my app I have separate repository class for network operations. In repository class I am getting response from the server. How can I show Toast message send from the server in my main activity.

READ  [ANSWERED] android - Unity Touch.Phase.Position always returning (0,0,0)
Powered by Inline Related Posts

Below is my code:

Repository.java

public class MyRepository {

MutableLiveData<List<Facts>> mutableLiveData = new MutableLiveData<>();
    
Application application;

public MyRepository(Application application) {
    this.application = application;
}

public MutableLiveData<List<Facts>> getMutableLiveData(){

    Retrofit retrofit = RetrofitClient.getInstance();
    ApiService apiService = retrofit.create(ApiService.class);

    apiService.getFacts().subscribeOn(Schedulers.io())
                         .observeOn(AndroidSchedulers.mainThread())
                         .subscribe(new Observer<List<Facts>>() {
                             @Override
                             public void onSubscribe(Disposable d) {

                             }

                             @Override
                             public void onNext(List<Facts> facts) {

                                 if(facts.size() > 0 && facts != null){

                                     mutableLiveData.setValue(facts);
                                 }
                             }

                             @Override
                             public void onError(Throwable e) {

                                 TastyToast.makeText(application,e.getMessage(),TastyToast.LENGTH_SHORT,
                                         TastyToast.ERROR).show();
                             }

                             @Override
                             public void onComplete() {

                             }
                         });

       return mutableLiveData;
  }
 }

FactsViewModel.java

public class FactsViewModel extends AndroidViewModel {

MyRepository repo;

public FactsViewModel(@NonNull Application application) {
    super(application);

    repo = new MyRepository(application);
  }

public LiveData<List<Facts>> getAllFacts(){

    return repo.getMutableLiveData();
  }
}

MainActivity.java

 private void myFacts(){

    FactsViewModel viewModel = new ViewModelProvider(this).get(FactsViewModel.class);  

    viewModel.getAllFacts().observe(this, new Observer<List<Facts>>() {
       @Override
       public void onChanged(List<Facts> facts) {

           adapter = new FactsAdapter(facts,getActivity());
           recycle.setAdapter(adapter);
       }
   });

}

How can I show error toast messages in MainActivity?

Comments

Comment posted by Taki

You have to get the response which contains the toast from your server and then simply show it in your mainactivity

Comment posted by Digvijay

How explain it I am fetching toast message in repository how can I get message in

Comment posted by Taki

did you get the toast from your server ?

Comment posted by Digvijay

yeah when I get error message from the server it shows in MainaAtivity but progress bar keeps on showing it should be hide.

Comment posted by Taki

After showing the toast , you have to simply hide or set the progressbar visibility t ogone

Recent Posts

  • How can I play with my cat without toys?
  • What is a bag pipe band called?
  • Are Honda Civics actually fast?
  • Are Yankee candles toxic?
  • How do I pair my Michael Kors smartwatch with my Android?

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuántas
  • ¿Cuánto
  • ¿Que
  • ¿Quién
  • 90” and 108” so you may have to round up to the nearest size.
  • and delete any Spotify folders from it. Once this is done
  • Android
  • Are
  • At
  • Bei
  • blink
  • C'est
  • Can
  • carbs
  • Comment
  • Did
  • Do
  • Does
  • During
  • For
  • Has
  • How
  • In
  • Is
  • Ist
  • Kann
  • Können
  • nouveau
  • On
  • or 108 inches.2020-08-03
  • Où
  • owning
  • Pourquoi
  • Puis-je
  • Quand
  • Quante
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • spiritual
  • tap the downward-facing arrow on the top left. A downward-facing arrow will appear underneath each song in the album; they'll turn green as the download completes.2020-07-28
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welcher
  • Welches
  • Welke
  • Wer
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Whose
  • Why
  • Wie
  • Will
  • Wo
  • Woher
  • you will receive two curtains each with the same measurements of width 66"" (168cm) x drop 54""(137cm).
  • you'll see a green downward-facing arrow next to each song.2021-02-26
©2023 Who Do Is | Powered by SuperbThemes & WordPress