To process the live data for signals, I defined following class SignalsViewModel and when I call the updateSignals function, it get stuck and doesn't run the next command.
I create the signalsViewModel using following code.
signalsViewModel = new ViewModelProvider(this).get(SignalsViewModel.class);
When I update the set the live data, app get stuck in the following function and doesn't run the next command.
// Get Stuck here.
signalsViewModel.updateSignals(booleen);
// Doesn't run the following command
sendNextRequest();
Here is the class definition of SignalsViewModel.
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import java.util.Arrays;
public class SignalsViewModel extends ViewModel {
private final MutableLiveData<boolean[]> signals = new MutableLiveData<>(new boolean[4]);
/**
* Returns a LiveData that observers can watch.
*/
public LiveData<boolean[]> getSignals() {
return signals;
}
/**
* Updates the signals. Observer only notified if values actually changed.
*/
public void updateSignals(boolean[] newSignals) {
if (newSignals == null || newSignals.length != 4) {
throw new IllegalArgumentException("Signals array must have exactly 4 elements.");
}
boolean[] oldSignals = signals.getValue();
if (!Arrays.equals(oldSignals, newSignals)) {
// Make a copy to prevent external modification
signals.setValue(Arrays.copyOf(newSignals, newSignals.length));
}
}
}
It was the thread issue. I called the function in the background thread and it didn't work. Should call in the UI thread.
'''
runOnUiThread (new Thread(new Runnable() {
public void run() {
signalsViewModel.updateSignals(booleen);
}
}));
'''