rebo / atomic_hooks

4 stars 6 forks source link

ObserveChangeReactiveState::on_change does not give previous state #6

Open arn-the-long-beard opened 4 years ago

arn-the-long-beard commented 4 years ago

Hello :wave:

Instead of spamming the discord, I think it might be better to report the issues there :smile:

Okay here is the issue I have with the unit test

    #[test]
    fn test_on_changes_on_atom() {
        let a = a();
        let mut previous = 99;
        let mut current = 99;
        a.on_change(|p, c| {
            previous = *p;
            current = *c;
        });
        assert_eq!(previous, 0); //todo : should we expect None when init ?
        assert_eq!(current, 0);
        a.set(1);
        a.on_change(|p, c| {
            previous = *p;
            current = *c;
        });
        assert_eq!(previous, 0);
        assert_eq!(current, 1);
        a.set(1);
        a.on_change(|p, c| {
            previous = *p;
            current = *c;
        });
        assert_eq!(previous, 0);
        assert_eq!(current, 1);
        a.set(2);
        a.on_change(|p, c| {
            previous = *p;  // <----- return 0 instead of 1
            current = *c;
        });
        assert_eq!(previous, 1, "we should get 1");
        assert_eq!(current, 2, "we should get 2");
    }

When I debug carefully, I see that this code does not behave as expected

   fn on_change<F: FnOnce(&T, &T) -> R, R>(&self, func: F) -> R {
        let previous_value_access = crate::hooks_state_functions::use_state(|| self.get());
        previous_value_access.get_with(|previous_value| {
            self.observe_with(|new_value| func(previous_value, new_value))
        })
    }

I do not understand much the code inside hooks_state_functions, but I understand that we get the initial value there instead of previous value.

Also all the methods for ObserveChangeReactiveState are failing for unit test. Not sure if it is related to the same issue.

Is there a way we can fix it ?