Search code examples
javaandroidandroid-livedataandroid-viewmodelmutablelivedata

textView is not updating while observer is running


I'm trying the LiveData and ViewModel architecture. I have a simple counter in the ViewModel which is observed on MainActivity. I am able to confirm that the data is acquired in onChanged of the observer, but the problem is the textView is not updating every increment and I'm only getting the last count which 9.

Here is my code.

MainActivity

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    binding.setNumber(model);
    binding.setLifecycleOwner(this);

    model = ViewModelProviders.of(this).get(MainActivityViewModel.class);

    textView = findViewById(R.id.textView);

    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                model.incrementNumber();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    model.getNumber().observe(this, new Observer<String>() {
        @Override
        public void onChanged(final String s) {
            Log.d(TAG, s);
            textView.setText(s);
        }
    });

}

And here is the viewModel

public class MainActivityViewModel extends AndroidViewModel {

MutableLiveData<String> number;

public MainActivityViewModel(@NonNull Application application) {
    super(application);
    number = new MutableLiveData<String>("0");
}

public MutableLiveData<String> getNumber(){
    return number;
}

public void incrementNumber() throws InterruptedException {
    for(int x = 0; x < 10 ; x++){

        Thread.sleep(500);

        number.setValue(String.valueOf(x));
    }

}

}


Solution

  • Try using a main thread Handler.postDelayed that will increment the number and post again to the Handler instead of Thread.sleep.