0

I have a function like this:

private data: MyCustomDataObject;
private getData(): boolean {
    let val: boolean = true;   // variable declared
    this.service.callMethod().subscribe(data => {
        this.data = data;
        if (data == null) {
            val = false;   // val declared above is not updating
        } 
    });
return val; // this is still true, should be false
}

How come val isn't updating?

5
  • Where do you use val? (or getData)? Commented Jun 6, 2018 at 19:09
  • 3
    Is subscribe asynchronous? If so, getData is returning before the function you pass to subscribe ever runs Commented Jun 6, 2018 at 19:10
  • getData is called from another method in the same class, and val is used in that same method that calls getData Commented Jun 6, 2018 at 19:11
  • Judging by the naming scheme, the function you pass to subscribe is just a callback for when something changes. Am I right in guessing that? Commented Jun 6, 2018 at 19:13
  • @MichaelHulet Yes that's right Commented Jun 6, 2018 at 19:13

1 Answer 1

2

What's happening here is that subscribe takes the function you give it, and hangs onto it for later, when some event happens. It doesn't actually run your function when you pass it. Because of this, the getData function moves on without your callback ever being called, so the value of val never changes before getData returns. If you want it to return false, you'll need to change val outside of the callback that you pass to subscribe.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.