Skip to content
This repository has been archived by the owner on Feb 5, 2024. It is now read-only.

Commit

Permalink
added transaction support for autorun method
Browse files Browse the repository at this point in the history
  • Loading branch information
capaj committed Apr 18, 2016
1 parent 29032bd commit e1ce11a
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 3 deletions.
4 changes: 2 additions & 2 deletions benchmark-results.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mobX create observable, autorun and dispose x 39,205 ops/sec ±5.73% (71 runs sampled)
mobX create observable, autorun and dispose x 40,866 ops/sec ±3.94% (75 runs sampled)

proxevable create observable, autorun and dispose x 76,322 ops/sec ±5.73% (73 runs sampled)
proxevable create observable, autorun and dispose x 75,569 ops/sec ±5.37% (72 runs sampled)

Fastest is proxevable create observable, autorun and dispose

22 changes: 21 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ const subscriptions = new WeakMap()

const _ = require('lodash')
let autorunFn = null
const transactionStack = []
const autorunsAfterTransaction = new Set()

const transactionallyCall = (cb) => {
if (transactionStack.length > 0) {
autorunsAfterTransaction.add(cb)
} else {
cb()
}
}

const api = {
observable: (source) => {
Expand Down Expand Up @@ -50,7 +60,7 @@ const api = {
if (thisSubscriptions[sKey]) {
thisSubscriptions[sKey].forEach((callback) => {
autorunFn = callback
callback()
transactionallyCall(callback)
})
}
autorunFn = null
Expand Down Expand Up @@ -111,6 +121,16 @@ const api = {
return () => {
fn.$onDispose.forEach((cb) => cb())
}
},
transaction: (fn) => {
fn.toBeCalledAfter = new Set()
transactionStack.push(fn)
fn()
if (fn === transactionStack[0]) {
autorunsAfterTransaction.forEach((cb) => {
cb()
})
}
}
}

Expand Down
File renamed without changes.
20 changes: 20 additions & 0 deletions test/transaction.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import test from 'ava'
import {observable, autorun, transaction} from '../index'

test('transaction batches', t => {
let c = 0
const a = observable({g: 0})
autorun(() => {
const ident = (v) => v
ident(a.g)
c += 1
})
transaction(() => {
a.g = 1
transaction(() => {
a.g = 2
a.g = 3
})
})
t.truthy(c === 2)
})

0 comments on commit e1ce11a

Please sign in to comment.