Skip to content

Rxjs equivalent of scan? #3524

Answered by urugator
rickmed asked this question in Q&A
Discussion options

You must be logged in to vote

Side effects in computeds are generally discouraged, but it's probably fine to mutate non-observable that acts as a local state and is not exposed to anything else:

function scan(reduce, initialValue, keepAlive = false) {
  let prevValue = initialValue;  
  let index = 0;
  const _computed = computed(() => {    
    prevValue = reduce(prevValue, index)
    index++;
    return prevValue;
  }, { keepAlive })
  if (!keepAlive) {
     // Reset if unsubscribed
    onBecomeUnobserved(_computed, () => {
      prevValue = initialValue;
      index = 0;
    })
  }  
  return {
    get() {
      return _computed.get();
    } 
  }
}

Did not test.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by rickmed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants