Javascript – How to make real-time value changes in Java like React.js

How to make real-time value changes in Java like React.js… here is a solution to the problem.

How to make real-time value changes in Java like React.js

I got used to React .js for 6 months and started developing an app for my Android app from scratch.

In React.js, everything it does when the boolean value changes from false to true:

this.state = {
    checkmarkChecked: false
}
if (this.state.checkmarkChecked) {
    If the checkmarkChecked is true
    TODO: show all checks
} else {
    If the checkmarkChecked is false
    TODO: hide all checks
}

If checkmarkChecked is toggled to true, it calls true to display.

Now I’m new to Android developing Java and I tried one of them:

//onCreate
while (true) {
    if (checkmarkChecked) {
        System.out.println("True");
    } else {
        System.out.println("False");
    }
}

Actually, while(true) causes my app to get stuck at the beginning.

Solution

You can use MutableLiveData that contains Boolean and register an activity to observe it using .observe().

Whenever this boolean

value changes, the onChanged() callback is triggered by the new value of the boolean value.

public class MainActivity extends AppCompatActivity {

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

final MutableLiveData<Boolean> state = new MutableLiveData<>(false);
    
state.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean newValue) {
                if (newValue) {
                    Toast.makeText(MainActivity.this, "True", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "False", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
Button myButton = findViewById(..);
        
myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                state.setValue(!state.getValue());
            }
        });
        
}
}

A button to toggle the boolean value to test it

Related Problems and Solutions