mobx icon indicating copy to clipboard operation
mobx copied to clipboard

Derived arrays in MobX

Open nardi opened this issue 10 years ago • 40 comments

What is the best way to define a derived array in MobX? By that I mean, if I have an observable array var a = observable(['foo', 'bar']); and I then perform an operation on it such as

function foo(a) {
  return a.filter(s => s.indexOf('foo') !== -1);
}
var b = foo(a);

how do I do this in a way so that:

  1. b is an ObservableArray itself
  2. adding the string 'foobar' to a also updates b to ['foo', 'foobar']

It seems as if I either have to construct a new observable array with the contents of a.filter(...) to have 1 but not 2, or I have to use a computed observable to have 2, but I can then only get the contents out as a regular array by doing b.get() and so I don't have 1.

I would maybe expect calling something like .filter(...) on an observable array would return a read-only observable array whose contents contain everything in the original array (subject to changes) that passes the filter function. So adding or deleting an element in the original array is propagated to the filtered array. Is this something already possible or is it worth implementing using array.observe?

nardi avatar Mar 21 '16 09:03 nardi

Hi @nardi,

Currently approach 2 is the idiomatic way: var filteredArray = computed(() => a.filter(...)). As noticed this does indeed not result in a new observable array as value from the computation. But the computation itself is cached and will yield the same result as long as the original array doesn't change.

I have planned to add special filter, map, slice etc operations that returns observable arrays as that would potentially result in huge performance benefits, but so far nobody really needed it yet as the computed arrays are usually already fast enough. The reason for that is probably that most people use observable arrays to power their react components, and React would not benefit directly from smartly updating observable arrays in all cases, as it will always map the complete list to re-create child components (see for details this SO question).

That being said, I did some successful experimenting in the past with smart map and filter functions that intelligently update the result array only for the changed items and I plan to add this feature to MobX sooner or later. If you need it, sooner ;-).

A bit elaborate so I hope this answers your question, otherwise just let me now.

mweststrate avatar Mar 21 '16 19:03 mweststrate

@mweststrate I would love to see these derived arrays in mobx. It would help with awfully big arrays, which are cumbersome to reiterate on each small change.

capaj avatar Mar 30 '16 10:03 capaj

Give me a few weeks, but I'll definitely plan on adding this. Which operations would you need (first)? map, filter, slice? Maybe sort?

Op wo 30 mrt. 2016 om 12:34 schreef Jiri Spac [email protected]:

@mweststrate https://github.com/mweststrate I would love to see these derived arrays in mobx. It would help with awfully big arrays, which are cumbersome to reiterate on each small change.

— You are receiving this because you were mentioned.

Reply to this email directly or view it on GitHub https://github.com/mobxjs/mobx/issues/166#issuecomment-203371634

mweststrate avatar Mar 30 '16 18:03 mweststrate

@mweststrate thanks, order of importance for me: 1.filter 2.sort 3. slice 4. map

capaj avatar Mar 30 '16 18:03 capaj

For me it would be filter, map, sort. I don't really see slice as important, nor am I sure what the semantics would be - I my case I wouldn't care about the actual numerical index of elements, as long as they are stored in unmodified order (except for sort) and enumerable.

nardi avatar Apr 05 '16 06:04 nardi

  1. Filter
  2. Sort (and a new sortBy à la lodash would be EXCELLENT)
  3. Map

danieldunderfelt avatar May 28 '16 15:05 danieldunderfelt

I have planned to add special filter, map, slice etc operations that returns observable arrays as that would potentially result in huge performance benefits.

Just wondering how would it improve perf? Is it similar to view vs materialized view in SQL?

AriaFallah avatar May 28 '16 16:05 AriaFallah

@AriaFallah yeah it is very similar to that indeed. Instead of always remapping the array, the splices can be observed and applied (after mapping) to the target array. Etc. I made something similar in the past and it was quite doable and very efficient. Only nasty one is sort, but still doable I think with binary search / insertion.

mweststrate avatar May 30 '16 15:05 mweststrate

If you base MobX observables over xstream or even rx all these problems go away, just saying.

benjamingr avatar Jun 12 '16 15:06 benjamingr

@benjamingr

That sounds interesting. Could you elaborate?

AriaFallah avatar Jun 12 '16 22:06 AriaFallah

@benjamingr no it doesn't relate, streams map events in time, this is about mapping values in space.

Simply put:

const todos = ["fetch coffee", "fetch tea"]
const upperCaseTodos =  todos.map(s => s.toUpperCase())

MobX already has the means to already reflect the changes in todos automatically in upperCaseTodos. This is about optimizing that changing one of the specific todo's results in only that value being remapped, and not all of them. createTransformer can already do that, this story is about generalizing that concept for all array operations.

mweststrate avatar Jun 13 '16 06:06 mweststrate

That being said, I did some successful experimenting in the past with smart map and filter functions that intelligently update the result array only for the changed items and I plan to add this feature to MobX sooner or later. If you need it, sooner ;-).

@mweststrate I've done some work like this using CanJS's computes and red-black binary trees in the canjs/can-derive project. Specifically on the .filter() transformation.

Unfortunately, I didn't achieve the performance gains I was hoping for: Be proactive, not reactive – Faster DOM updates via change propagation

I'm stoked to learn how your approach compares.

akagomez avatar Jun 17 '16 05:06 akagomez

I think my issue is similar: I would like that a computed function returning an array can be observed like observable arrays, i.e., that I can observe if some elements are added/removed from the computed array.

aravantv avatar Jul 23 '16 21:07 aravantv

Mmmh, just saw that the observe method of ObservableArrays actually just conform to the (former) ES7 proposal but does not allow to observe what was added/removed, so that would actually be my first wish...

aravantv avatar Jul 23 '16 21:07 aravantv

@aravantv nope that knowledge is already available, additions and removals are just expressed in the form of 'splices'.

You could achieve roughly what you want by doing something like:

var source = observable([])
var derived = observable([])

source.observe(change => {
   // inspect the splice / update and update the relevant parts of the derived array
})

Depending on your computation that might either be trivial or a very complicated thing to do :)

mweststrate avatar Jul 24 '16 13:07 mweststrate

I'm incredibly excited for these new smart map, filter, slice etc. array functions. What's the status those features?

Seems like it would make changing and optimizing big data sets without doing much work. Also will be quite powerful optimizing createTransformation even further

ckwong90 avatar Jul 31 '16 01:07 ckwong90

I'm still planning on this, but not in the near future (next month) as there don't seem to be much need for these kind of optimizations so far. If in dire need, a case specific solution using splices will often not be that hard (a generic solution is harder, as there need to be clear semantics on the influence of transactions, arbitrary observables used in mapping functions etc, but I already build something similar in a predecessor of MobX)

mweststrate avatar Aug 01 '16 20:08 mweststrate

I created a gist for a linked filtered observable array function: https://gist.github.com/mavericken/f0eb2cc5699c3a406aabe7582d87fa54 I haven't tested it sufficiently yet, but I wanted to add it to this case before I forgot about it.

mavericken avatar Jan 13 '17 04:01 mavericken

Hello, any news about this topic? I'm implementing a 'model' like structure based on MobX and I cannot find a way to easily filter and sort (in chain) an observable array.

cescox avatar Mar 27 '17 12:03 cescox

Just going to add my 2 cents to this as well, array.filter would be awesome if optimized, @computed doesn't work too well for us when we start to deal with thousands of items.

dzhng avatar Jun 01 '17 13:06 dzhng