Reactive Programming – Observables

Mastering observables

Important:A newer version of this software with updated documentation is available. Visit the Couchbase Developer Portal for more information.

The following guide helps you getting up to speed with asynchronous programming and Observables in particular. This guide is not tied to the Java SDK exclusively and aims to give you a general understanding of how to build full stack asynchronous applications.

Motivation

Asynchronous and reactive methodologies allow you to better utilize system resources. Instead of wasting a thread waiting for network (or disk) IO, it can be fully utilized to perform other work instead.

A broad range of technologies exists to facilitate this style of programming, ranging from the very limited and not really usable java.util.concurrent.Future, to full blown libraries and runtimes like Akka (and everything in between). For a database driver, the following requirements must be met:

  • Rich functionality
  • Interoperable and not opinionated
  • Performant
  • Small dependency and runtime footprint

After evaluating the requirements and solutions closely, one library stood out: RxJava. It has a very rich set to compose asynchronous workflows, has no dependencies on its own and is used at high-profile companies like Netflix. The Rx model (more on that a little later) is mature and well-thought and the community is vibrant.

We hope that once you read through the introduction and get more familiar with the concept, you never want to go back. We certainly don’t. That said, we fully support blocking operations as well, so you can still use a traditional blocking-based model if you absolutely want to.

The next section gradually introduces you into the world of Observables, the first step to reactive masterhood. If you want to learn more about the motivation, read on here.

Java 8, Lambdas and Anonymous Classes

Before jumping into the details, one thing warrants clarification: RxJava, and therefore the Java SDK fully supports Java 8. This brings some great improvements, most prominently support for lambdas and method references.

Because the Java SDK has support for Java 6 and 7, most of the examples shown in the documentation use anonymous classes instead of lambdas. You are free and even encouraged to use them if you are able to, but Java 8 on production servers is still a few months/years away at most companies.

That said, we expect the SDK to be around for a long time and want to pave the way for the future right now. To whet your appetite, compare Java 6 code to Java 8 (same code):

// Loads 3 documents in parallel
Observable
    .just("doc1", "doc2", "doc3")
    .flatMap(new Func1<String, Observable<JsonDocument>>() {
        @Override
        public Observable<JsonDocument> call(String id) {
            return bucket.get(id);
        }
    }).subscribe(new Action1<JsonDocument>() {
        @Override
        public void call(JsonDocument document) {
            System.out.println("Got: " + document);
        }
    });
// Loads 3 documents in parallel
Observable
    .just("doc1", "doc2", "doc3")
    .flatMap(bucket::get)
    .subscribe(document -> System.out.println("Got: " + document));

Also, RxJava has support for other languages like Scala, Groovy or Clojure. If you are using one of those languages, please refer to the RxJava documentation on how to use the adapters.

Understanding Observables

You can think of a Observable as the push-based, asynchronous cousin (“dual”) of the pull-based, synchronous Iterable. The contract of a Observable is that zero to N data events can happen, followed by a complete event. In addition, an error event can happen at any time, also completing the Observable.

Table 1. The Duality of Iterable & Observable
Event Iterable (Pull) Observable (Push)
retrieve data T next() onNext(T)
discover error throws Exception onError(Exception)
complete returns onCompleted()

A Observable can also be converted into a BlockingObservable, which then, unsurprisingly, behaves very much like a Iterable.

The key element to take away is that a Observable<T> can emit 0 to N events, which is very different of a Future<T>, which only contains one value. Once you start to work on streams instead of single values, you will very much appreciate this fact.

Also, important to understand is that by definition, a Observable does not imply that the underlying code is executed asynchronously. As a consumer of an Observable, you leave the actual implementation to the supplier, who is able to change it later on without you having to adapt your code. Imagine, you are consuming this API:

public interface FooService {
    Observable<String> load();
}

It could be that when load() is called, the String value is fetched right out of a Map in memory (or even a hard-coded value). In this case, there is no need to move the execution away from the caller thread, because the value will be returned instantaneously. If at a later point the implementation needs to be changed so that the String is loaded through a web service (which introduces latency and other semantics), the API doesn’t need to be changed, because the underlying implementation is free to move it to a Scheduler.

Consuming Observables

The first thing you want to do when working with Observables is to consume them. Consuming a Observable means subscribing to it. Here is an example which subscribes and prints out all the items emitted:

Observable
    .just(1, 2, 3)
    .subscribe(new Subscriber<Integer>() {
        @Override
        public void onCompleted() {
            System.out.println("Completed Observable.");
        }

        @Override
        public void onError(Throwable throwable) {
            System.err.println("Whoops: " + throwable.getMessage());
        }

        @Override
        public void onNext(Integer integer) {
            System.out.println("Got: " + integer);
        }
    });

This prints:

Got: 1
Got: 2
Got: 3
Completed Observable.

You can see that our Observer gets notified of every event and also receives the completed event.

Note:A well-formed Observable will invoke its Subscriber’s onNext method zero or more times, and then will invoke either the onCompleted or onError method exactly once.

You can also test the error case by throwing an artificial exception when the value 2 is emitted:

Observable
    .just(1, 2, 3)
    .doOnNext(new Action1<Integer>() {
        @Override
        public void call(Integer integer) {
            if (integer.equals(2)) {
                throw new RuntimeException("I don't like 2");
            }
        }
    })
    .subscribe(new Subscriber<Integer>() {
        @Override
        public void onCompleted() {
            System.out.println("Completed Observable.");
        }

        @Override
        public void onError(Throwable throwable) {
            System.err.println("Whoops: " + throwable.getMessage());
        }

        @Override
        public void onNext(Integer integer) {
            System.out.println("Got: " + integer);
        }
    });

This prints:

Got: 1
Whoops: I don't like 2

The first value gets through without problems, the second value throws an exception and therefore terminates the observable (and no subsequent values are allowed to be emitted after a error event).

Note:The subscribe method also returns a Subscription which you can use to unsubscribe and therefore do not receive further events.

Even if you don’t unsubscribe explicitly, operations like take do that for you implicitly. The following code only takes the first five values and then unsubscribes:

Observable
    .just("The", "Dave", "Brubeck", "Quartet", "Time", "Out")
    .take(5)
    .subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {
            System.out.println("Completed Observable.");
        }

        @Override
        public void onError(Throwable throwable) {
            System.err.println("Whoops: " + throwable.getMessage());
        }

        @Override
        public void onNext(String name) {
            System.out.println("Got: " + name);
        }
    });

This prints:

Got: The
Got: Dave
Got: Brubeck
Got: Quartet
Got: Time
Completed Observable.
Note:If you take a close look at the API, subscribe() can be fed with either an Observer or a Subscriber. Unless you are implementing a custom Observer, always use Subscriber (because otherwise it will be wrapped in one internally anyway and you are saving unnecessary object allocations).

You do not need to implement the full Subscriber every time. If you are only interested in the data events, you can subscribe like this:

Observable
    .just(1, 2, 3)
    .subscribe(new Action1<Integer>() {
        @Override
        public void call(Integer integer) {
            System.out.println("Got: " + integer);
        }
    });

Be aware though that if an error happens, the following exception will be propagated:

Exception in thread "main" rx.exceptions.OnErrorNotImplementedException
	at rx.Observable$36.onError(Observable.java:8412)
	at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:128)
	at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:97)
	at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:67)
	at rx.internal.operators.OperatorDoOnEach$1.onNext(OperatorDoOnEach.java:78)
	at rx.internal.operators.OnSubscribeFromIterable$IterableProducer.request(OnSubscribeFromIterable.java:76)
	...

It is recommended to always implement an error handler right from the beginning, since things can and will go wrong at some point. It can come in handy though if you just want to try things out quickly or for illustrative purposes.

From Async to Sync

As long as your Observable works on the same thread all the time, there is no need for communication between threads since only one is executing. When your Observable flow gets executed on a different thread though, you need to take some extra care to make sure you are not missing values. This is not specific to Observables though, every time you need to deal with parallel threads you need to think about synchronization and communication.

The following code emits a increasing value every second, and this is done on a different thread:

public static void main(String... args) {
    Observable
        .interval(1, TimeUnit.SECONDS)
        .subscribe(new Action1<Long>() {
            @Override
            public void call(Long counter) {
                System.out.println("Got: " + counter);
            }
        });
}

It works perfectly fine, the only problem is though chances are you won’t see anything printed out. This is because your main thread exits before the background thread had a chance to run and emit values.

A common way to deal with such a situation is to add a CountDownLatch, which allows you to synchronize between different threads. One thread counts down the latch, the other one waits until it is counted down:

final CountDownLatch latch = new CountDownLatch(5);
Observable
    .interval(1, TimeUnit.SECONDS)
    .subscribe(new Action1<Long>() {
        @Override
        public void call(Long counter) {
            latch.countDown();
            System.out.println("Got: " + counter);
        }
    });

latch.await();

This prints and then exits:

Got: 0
Got: 1
Got: 2
Got: 3
Got: 4
Note:One common mistake is to use Thread.sleep() instead of a latch to synchronize the execution between threads. This is a bad idea because it not really synchronizes anything, but just keeps one thread alive for a specific amount of time. If the actual calls take less time you are wasting time, and if it takes longer you won’t get the desired effect. If you do this in unit tests, be prepared for a good amount of non-determinism and randomly failing tests. Always use a CountDownLatch.

A technique unique to Observables is to convert it into a BlockingObservable to achieve the same effect. In simple terms, it converts a Observable into a Iterable and making it execute on the caller thread, blocking it until one or more values arrive. This technique is used extensively in the documentation to show concepts, while not having to deal with CountDownLatches all the time. It can also be used if you for some reason are not able to use asynchronous computations.

The conversion itself doesn’t do any blocking in the first place, only subsequent calls will:

// This does not block.
BlockingObservable<Long> observable = Observable
    .interval(1, TimeUnit.SECONDS)
    .toBlocking();

// This blocks and is called for every emitted item.
observable.forEach(new Action1<Long>() {
    @Override
    public void call(Long counter) {
        System.out.println("Got: " + counter);
    }
});

Since this will run forever, you are free to chain any asynchronous computations before. So you ca build an asynchronous workflow and then block at the very end. This resembles the same code as with the CountDownLatch before:

Observable
    .interval(1, TimeUnit.SECONDS)
    .take(5)
    .toBlocking()
    .forEach(new Action1<Long>() {
        @Override
        public void call(Long counter) {
            System.out.println("Got: " + counter);
        }
    });

If you know that only a single value is every returned, you can use the single() method:

int value = Observable
    .just(1)
    .toBlocking()
    .single();

Be aware though that if more items get emitted, you get an exception:

Exception in thread "main" java.lang.IllegalArgumentException: Sequence contains too many elements
	at rx.internal.operators.OperatorSingle$1.onNext(OperatorSingle.java:58)
	at rx.internal.operators.OnSubscribeFromIterable$IterableProducer.request(OnSubscribeFromIterable.java:76)
	at rx.Subscriber.setProducer(Subscriber.java:148)
	at rx.Subscriber.setProducer(Subscriber.java:144)
	....

The same thing happens if no value gets emitted:

Exception in thread "main" java.util.NoSuchElementException: Sequence contains no elements
	at rx.internal.operators.OperatorSingle$1.onCompleted(OperatorSingle.java:82)
	at rx.internal.operators.OnSubscribeFromIterable$IterableProducer.request(OnSubscribeFromIterable.java:79)
	at rx.Subscriber.setProducer(Subscriber.java:148)
	at rx.Subscriber.setProducer(Subscriber.java:144)
	at rx.Subscriber.setProducer(Subscriber.java:144)
	at rx.Subscriber.setProducer(Subscriber.java:144)
	....

As an alternative, you can use singleOrDefault() so that a fallback value gets returned.

You can use this technique with the Java SDK if you are loading a document and it does not exist:

JsonDocument doc = bucket.get("id").toBlocking().singleOrDefault(null);
if (doc == null) {
    System.err.println("Document not found!");
} else {
    System.out.println(doc);
}

If you check out the API documentation of the BlockingObservable, you will discover many more possibilities, including iterators or grabbing the first and/or last valuess.

One last thing that comes in handy with blocking calls: sometimes you want to collect all emitted values into a list. You can combine the blocking calls with the toList() operator to achieve something like this:

List<Integer> list = Observable
    .just(1, 2, 3)
    .toList()
    .toBlocking()
    .single();

// Prints: [1, 2, 3]
System.out.println(list);

Creating Observables

There are many ways to create Observables, and you’ve already seen just() and interval(). There are many more of those convenience methods available on the Observable class, but they all boil down to the create() method. You can simulate the example from before with this:

Observable.create(new Observable.OnSubscribe<Integer>() {
    @Override
    public void call(Subscriber<? super Integer> subscriber) {
        try {
            if (!subscriber.isUnsubscribed()) {
                for (int i = 0; i < 5; i++) {
                    subscriber.onNext(i);
                }
                subscriber.onCompleted();
            }
        } catch (Exception ex) {
            subscriber.onError(ex);
        }
    }
}).subscribe(new Action1<Integer>() {
    @Override
    public void call(Integer integer) {
        System.out.println("Got: " + integer);
    }
});

Every time a Subscriber subscribes, the call() method is executed. You can then call onNext, onComplete and onError as you wish, but keep in mind that both onComplete and onError should only be called once, and afterwards no subsequent onNext is allowed to follow so that the contract is met.

You can see that no blocking call is needed, because the Observable is completely handled on the current thread. In the section on Schedulers, you learn more about that.

Note:This example shows why it is crucial to call subscribe() on the Observable, because only such a call triggers the actual execution of the pipeline. This is a little different with Subjects, which are covered later in this guide. Nevertheless, always call subscribe() on your Observables.

Refer to the RxJava documentation on many more methods that you can use to create Observables. If you are dealing with the Java SDK, in most places this is done for you, but there are situation where it comes in handy.

The Java SDK does not expose bulk methods anymore on the API, because you can do this already with the help of Observables. Compare these two examples, one only loads one document, the other loads a few (you’ll learn about flatMap() in the next section):

// Loads one document and prints it:
bucket
    .get("doc1")
    .subscribe(new Action1<JsonDocument>() {
        @Override
        public void call(JsonDocument document) {
            System.out.println("Got: " + document);
        }
    });
// Loads 3 documents in parallel
Observable
    .just("doc1", "doc2", "doc3")
    .flatMap(new Func1<String, Observable<JsonDocument>>() {
        @Override
        public Observable<JsonDocument> call(String id) {
            return bucket.get(id);
        }
    }).subscribe(new Action1<JsonDocument>() {
        @Override
        public void call(JsonDocument document) {
            System.out.println("Got: " + document);
        }
    });

Transforming Observables

Observables can transform their values in various ways. One of the most basic ones is map(), which converts the incoming value into a different one. You surely like division, so here is the FizzBuzz game:

Observable
    .interval(10, TimeUnit.MILLISECONDS)
    .take(20)
    .map(new Func1<Long, String>() {
        @Override
        public String call(Long input) {
            if (input % 3 == 0) {
                return "Fizz";
            } else if (input % 5 == 0) {
                return "Buzz";
            }
            return Long.toString(input);
        }
    })
    .toBlocking()
    .forEach(new Action1<String>() {
        @Override
        public void call(String s) {
            System.out.println(s);
        }
    });

The map function is used to convert the input number into a string and do some checks to satisfy the FizzBuzz game. As a more practical example, consider loading a document from the Java SDK and only extracting the firstname of a user before passing it on:

bucket
    .get("id")
    .map(new Func1<JsonDocument, String>() {
        @Override
        public String call(JsonDocument document) {
            return document.content().getString("firstname");
        }
    }).subscribe();

A variation of map() is called flatMap(), which allows you to do those transformations with asynchronous calles. Taking the example from above, we want to map from String (the document ID) to a JsonDocument (the loaded document). With a normal map(), call you would either need to block on the Observable or at some point deal with a Observable<Observable<JsonDocument>>.

Thankfully, flatMap() flattens the resulting values for us and return them into the original flow:

// Loads 3 documents in parallel
Observable
    .just("doc1", "doc2", "doc3")
    .flatMap(new Func1<String, Observable<JsonDocument>>() {
        @Override
        public Observable<JsonDocument> call(String id) {
            return bucket.get(id);
        }
    }).subscribe(new Action1<JsonDocument>() {
        @Override
        public void call(JsonDocument document) {
            System.out.println("Got: " + document);
        }
    });

You can see that flatMap() returns an Observable<T> whereas the normal map just returns <T>. You will use flatMap() a lot when dealing with flows like this, so keep it in mind.

Another helpful transformation is scan(). It applies a function to each value emitted by an Observable, sequentially, and emits each successive value. We can use it to aggregate values like this:

Observable
    .just(1, 2, 3, 4, 5)
    .scan(new Func2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer sum, Integer value) {
            return sum + value;
        }
    }).subscribe(new Action1<Integer>() {
        @Override
        public void call(Integer integer) {
            System.out.println("Sum: " + integer);
        }
    });

This prints:

Sum: 1
Sum: 3
Sum: 6
Sum: 10
Sum: 15

Finally, groupBy() comes in handy, which emits one Observable by each group, defined by a function. The following example emits two Observables, one for even and one for odd values:

Observable
    .just(1, 2, 3, 4, 5)
    .groupBy(new Func1<Integer, Boolean>() {
        @Override
        public Boolean call(Integer integer) {
            return integer % 2 == 0;
        }
    }).subscribe(new Action1<GroupedObservable<Boolean, Integer>>() {
        @Override
        public void call(GroupedObservable<Boolean, Integer> grouped) {
            grouped.toList().subscribe(new Action1<List<Integer>>() {
                @Override
                public void call(List<Integer> integers) {
                    System.out.println(integers + " (Even: " + grouped.getKey() + ")");
                }
            });
        }
    });

This prints:

[1, 3, 5] (Even: false)
[2, 4] (Even: true)

Combined with the Java SDK, this technique can be used to separate returned Documents based on their content. The following example uses a view to load all documents from the beer-sample bucket, groups them by type and counts the number of occurrences:

bucket
    .query(ViewQuery.from("my_design_doc", "my_view"))
    .flatMap(ViewResult::rows)
    .flatMap(ViewRow::document)
    .groupBy(document -> document.content().getString("type"))
    .subscribe(observable ->
        observable.count().subscribe(integer ->
            System.out.println(observable.getKey() + ": " + integer)
        )
    );

This code queries the view, extracts all rows, loads the full document for each row, groups it by the “type” property in the JSON document and then uses the count() operator to count the number of rows emitted by each observable. This prints something like:

brewery: 1412
beer: 5891

Filtering Observables

In addition to transforming Observables, you can also filter them. Filtering doesn’t change the emitted values itself, but rather how much and at which point (and if at all) they are emitted.

For example, you can filter based on some criteria:

// This will only let 3 and 4 pass.
Observable
    .just(1, 2, 3, 4)
    .filter(new Func1<Integer, Boolean>() {
        @Override
        public Boolean call(Integer integer) {
            return integer > 2;
        }
    }).subscribe();

Or take only the first N values emitted and then unsubscribe:

// Only 1 and 2 will pass.
Observable
    .just(1, 2, 3, 4)
    .take(2)
    .subscribe();

Or use only the first or last value emitted:

// Only 1 will pass
Observable
    .just(1, 2, 3, 4)
    .first()
    .subscribe();
// Only 4 will pass
Observable
    .just(1, 2, 3, 4)
    .last()
    .subscribe();

Finally, you can use distinct() to suppress duplicate values:

// 1, 2, 3, 4 will be emitted
Observable
    .just(1, 2, 1, 3, 4, 2)
    .distinct()
    .subscribe();
Note:distinct() also allows you to pass in a function which returns the key to select by. You can use this for example to separate out duplicate JsonDocuments.

Combining Observables

Multiple Observables can also be merged to form a combined one. Depending on how you want those to be merged, there are different operators available. Two of the most used ones are merge() and zip() which are covered here.

Merge really just merges all emitted values by the source observables in the order they arrive:

Observable
    .merge(evens, odds)
    .subscribe(new Action1<Integer>() {
        @Override
        public void call(Integer integer) {
            System.out.println(integer);
        }
    });

This prints something similar to:

2
4
6
8
10
1
3
5
7
9

With the zip operator, you can combine two streams in the stricly same order, defined by a function:

Observable<Integer> evens = Observable.just(2, 4, 6, 8, 10);
Observable<Integer> odds = Observable.just(1, 3, 5, 7, 9);

Observable
    .zip(evens, odds, (v1, v2) -> v1 + " + " + v2 + " is: " + (v1 + v2))
    .subscribe(System.out::println);

This zips each pairs togehter in order and prints:

2 + 1 is: 3
4 + 3 is: 7
6 + 5 is: 11
8 + 7 is: 15
10 + 9 is: 19

Error Handling

Error handling is a vital component of every real world application and needs to be considered from the start. RxJava provides sophisticated mechanisms to deal with errors that happen inevitably in your Observable flows.

In general, you want to react in the following ways:

  • Return a default value instead
  • Flip over to a backup Observable
  • Retry the Observable (immediately or with backoff)

Returning a default value is a good idea if you cannot afford to retry or you just don’t care (maybe because the flow is not absolutely crucial to your data flow). The following code throws an exception at the first emitted item, but falls back to a default value:

Note that you can pass in a function which also takes the Exception, so you can return different values for different exception types or use it for logging purposes.

// Prints:
// Default
// Oops: I don't like: Apples
Observable
    .just("Apples", "Bananas")
    .doOnNext(s -> {
        throw new RuntimeException("I don't like: " + s);
    })
    .onErrorReturn(throwable -> {
        System.err.println("Oops: " + throwable.getMessage());
        return "Default";
    }).subscribe(System.out::println);

You can also flip to a backup observable which will be called if the first one fails. The Java SDK has a getFromReplica() command which allows you to read stale data from its replicas and treat availability for consistency on reads. You can use this approach to fall back:

bucket
    .get("id")
    .onErrorResumeNext(bucket.getFromReplica("id", ReplicaMode.ALL))
    .subscribe();

Normally you want to have more control on which observable should be run next depending on the type of error. The following example will only go to the replica if a TimeoutException happened (if not the error is passed down):

bucket
    .get("id")
    .timeout(500, TimeUnit.MILLISECONDS)
    .onErrorResumeNext(new Func1<Throwable, Observable<? extends JsonDocument>>() {
        @Override
        public Observable<? extends JsonDocument> call(Throwable throwable) {
            if (throwable instanceof TimeoutException) {
                return bucket.getFromReplica("id", ReplicaMode.ALL);
            }
            return Observable.error(throwable);
        }
    });

Finally, it is possible to retry the Observable by resubscribing. This can be done as quickly as possible, or with a backoff interval (which is preferred when external resources are involved).

The following program desperately tries to read the numbers from 1 to 10, but a (not so hidden) flaw makes it randomly throw an exception. If that happens, the code retries. Since lots of values might be already emitted, we can use distinct() to filter those out.

Observable
    .just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    .doOnNext(integer -> {
        if (new Random().nextInt(10) + 1 == 5) {
            throw new RuntimeException("Boo!");
        }
    })
    .retry()
    .distinct()
    .subscribe(System.out::println);
Note:If you only want to retry for a max amount, replace the retry() with a retry(count) call.

If you want to retry with backoff, you can use a technique like the following:

Observable
    .range(1, 10)
    .doOnNext(integer -> {
        if (new Random().nextInt(10) + 1 == 5) {
            throw new RuntimeException("Boo!");
        }
    })
    .retryWhen(attempts ->
        attempts.zipWith(Observable.range(1, 3), (n, i) -> i)
        .flatMap(i -> {
            System.out.println("delay retry by " + i + " second(s)");
            return Observable.timer(i, TimeUnit.SECONDS);
        }))
    .distinct()
    .subscribe(System.out::println);

The attempts get passed into the retryWhen() method and zipped with the number of seconds to wait. The timer method is used to complete once its timer is done. If you run this code a few times to generate an exception (or more), you will see something similar to this:

1
2
3
4
delay retry by 1 second(s)
delay retry by 2 second(s)
5
6
7
8
9
10

Schedulers & Threads

Schedulers in RxJava are used to manage and control concurrency. Some operators implicitly use one and/or allow you to pass in a custom one.

RxJava ships with a bunch of preconfigured Schedulers by default, which are all accessible through the Schedulers class:

  • Schedulers.computation(): Event-loop style scheduler for purely computational work.
  • Schedulers.immediate(): Executes the work immediately on the current thread.
  • Schedulers.io(): Executes work on a Executor-backed pool which grows as needed.
  • Schedulers.newThread(): Creates a new thread for each unit of work.
  • Schedulers.trampoline(): Queues the work on the current thread and gets executed after the current work completes.
  • Schedulers.test(): Test scheduler used for testing and debugging, which allows manual advancing of the clock.

As a rule of thumb, the computation scheduler should always be used for in-memory processing, while the IO scheduler should only be used for blocking-style IO operations (so do not use it together with the Java SDK since it is asynchronous anyway!).

You can instruct an Observable to be executed on such a scheduler in four different ways:

  • Implicitly by using an operator that makes use of one
  • Explicitly by passing the Scheduler to such an operator
  • By using subscribeOn(Scheduler)
  • By using observeOn(Scheduler)

Operators like buffer, replay, skip, delay, parallel and so forth use a Scheduler by default if not instructed otherwise. A list of default schedulers can be found here: https://github.com/ReactiveX/RxJava/wiki/Scheduler#default-schedulers-for-rxjava-observable-operators

As a rule of thumb, all of those operators allow you to pass in a custom Scheduler if needed, but most of the time sticking with the defaults is a good idea.

Note:The Java SDK uses a internal scheduler similar to the computation Scheduler to proper isolate the inner mechanisms from user-land. It is possible to change that Scheduler through the environment, but not recommended.

If you want the whole subscribe chain to be executed on a specific scheduler, you use the subscribeOn() operator. Without a Scheduler set, the following code executes on the main thread:

Observable
    .range(1, 5)
    .map(integer -> {
        System.out.println("Map: (" + Thread.currentThread().getName() + ")");
        return integer + 2;
    })
    .subscribe(integer -> 
        System.out.println("Got: " + integer + " (" + Thread.currentThread().getName() + ")")
    );

This prints:

Map: (main)
Got: 3 (main)
Map: (main)
Got: 4 (main)
Map: (main)
Got: 5 (main)
Map: (main)
Got: 6 (main)
Map: (main)
Got: 7 (main)

If you add subscribeOn() somewhere in the flow (it doesn’t matter where):

Observable
    .range(1, 5)
    .map(integer -> {
        System.out.println("Map: (" + Thread.currentThread().getName() + ")");
        return integer + 2;
    })
    .subscribeOn(Schedulers.computation())
    .subscribe(integer ->
            System.out.println("Got: " + integer + " (" + Thread.currentThread().getName() + ")")
    );

You can see it is executed on the same thread, but on the computation thread pool:

Map: (RxComputationThreadPool-6)
Got: 3 (RxComputationThreadPool-6)
Map: (RxComputationThreadPool-6)
Got: 4 (RxComputationThreadPool-6)
Map: (RxComputationThreadPool-6)
Got: 5 (RxComputationThreadPool-6)
Map: (RxComputationThreadPool-6)
Got: 6 (RxComputationThreadPool-6)
Map: (RxComputationThreadPool-6)
Got: 7 (RxComputationThreadPool-6)

If you need tighter control which parts are executed on what pool, use observeOn(). Here, the order matters:

Observable
    .range(1, 5)
    .map(integer -> {
        System.out.println("Map: (" + Thread.currentThread().getName() + ")");
        return integer + 2;
    })
    .observeOn(Schedulers.computation())
    .subscribe(integer ->
            System.out.println("Got: " + integer + " (" + Thread.currentThread().getName() + ")")
    );

Everything before the observeOn call is executed in main, everything below in the Scheduler:

Map: (main)
Map: (main)
Map: (main)
Got: 3 (RxComputationThreadPool-6)
Got: 4 (RxComputationThreadPool-6)
Got: 5 (RxComputationThreadPool-6)
Map: (main)
Map: (main)
Got: 6 (RxComputationThreadPool-6)
Got: 7 (RxComputationThreadPool-6)

There is also a way to use Schedulers directly to schedule operations, please refer to the documentation here: https://github.com/ReactiveX/RxJava/wiki/Scheduler#using-schedulers

Subjects

A Subject is a hybrid between a Observable and a Subscriber. So it can both receive and emit events. Most of the time you don’t need Subjects and can handle everything fine through Observables alone, but there are certain cases when they come in handy.

There is a distinction between different Observables that have not been covered yet:

  • A cold Observable waits for a Subscription until it emits values and does this freshly for every Subscriber.
  • A hot Observable begins emitting values upfront and presents them to every subscriber subsequently. Subjects are hot Observables.
Note:Because of the network layer in between, the Java SDK needs to use Subjects for its request/response cycles. This also makes sense because if you subscribe twice to a bucket.get() call, you actually only want one network call instead of two.

Currently, there are four Subjects supported by RxJava, slightly differing in their functionality:

  • AsyncSubject: emits the last value (and only the last value) emitted by the source Observable, and only after that source Observable completes. (If the source Observable does not emit any values, the AsyncSubject also completes without emitting any values.)
  • BehaviorSubject: When an Subscriber subscribes to a BehaviorSubject, it begins by emitting the item most recently emitted by the source Observable (or an optional seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s).
  • PublishSubject: PublishSubject emits to a subscriber only those items that are emitted by the source Observable(s) subsequent to the time of the subscription.
  • ReplaySubject: ReplaySubject emits to any subscriber all of the items that were emitted by the source Observable(s), regardless of when the subscriber subscribes.

As an example: if you call bucket.get(), a AsyncSubject is created under the covers and returned to you immediately. In addition, it is passed down the IO layer and stored. When a response arrives from the server, the Subject is fed with the response and you get notified appropriately.

If you need to use a Subject, choose wisely which one to use in order to keep resource usage low (some of them cache data for subscribers) especially if you push lots of data through them. You can read more about them here: https://github.com/ReactiveX/RxJava/wiki/Subject

There is one last thing you need to know when dealing with Subjects: because you are not getting new values when resubscribing (since it’s cached), the following won’t work (doing a get call every second):

bucket
    .get("id")
    .delay(1, TimeUnit.SECONDS)
    .repeat()
    .subscribe();

This will only execute one get call, because subsequent attempts only load the cached value. For this reason Observable.defer() was added, which creates a new Observable for every subscriber that comes along:

Observable.defer(new Func0<Observable<JsonDocument>>() {
    @Override
    public Observable<JsonDocument> call() {
        return bucket.get("id");
    }
})
.delay(1, TimeUnit.SECONDS)
.repeat()
.subscribe();

Reference:
http://docs.couchbase.com/developer/java-2.0/observables.html
http://reactivex.io/intro.html

ReactJS – Using Flux

In this tutorial we will show you how to implement flux pattern in React applications. We will use Redux framework. The goal of the article is to present you the simplest example of every piece needed for connecting Redux andReact.

Step 1 – Installing Redux

We will install Redux via command prompt window.

C:\Users\username\Desktop\reactApp>npm install --save react-redux

Step 2 – Create Files and Folders

In this step we will create folders and files for our actions, reducers andcomponents. After we are done with it, this is how the folder structure will look like.

React Redux Folder Structure

Step 3 – Actions

Actions are JavaScript objects that use type property to inform about the data that should be sent to the store. We are defining ADD_TODO action that will be used for adding new item to our list. The addTodo function is action creator that returns our action and sets an id for every created item.

actions/actions.js

export const ADD_TODO = 'ADD_TODO'

let nextTodoId = 0;

export function addTodo(text) {
   return {
      type: ADD_TODO,
      id: nextTodoId++,
      text
   };
}

Step 4 – Reducers

While actions only trigger changes in the app, the reducers specify those changes. We are using switch statement to search for a ADD_TODO action. The reducer is a function that takes two parameters (state and action) to calculate and return updated state. The first function will be used to create new item, while the second one will push that item to the list. At the end we are using combineReducers helper function where we can add any new reducers we might use in the future.

reducers/reducers.js

import { combineReducers } from 'redux'
import { ADD_TODO } from '../actions/actions'

function todo(state, action) {
   switch (action.type) {
	
      case ADD_TODO:
         return {
            id: action.id,
            text: action.text,
         }
			
      default:
      return state
   }
}

function todos(state = [], action) {
   switch (action.type) {
	
      case ADD_TODO:
         return [
            ...state,
            todo(undefined, action)
         ]
			
      default:
      return state
   }
}

const todoApp = combineReducers({
   todos
})

export default todoApp

Step 5 – Store

The store is the place that holds the app’s state. It is very easy to create store once you have reducers. We are passing store property to the providerelement which wraps our route component.

main.js

import React from 'react'

import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'

import App from './App.jsx'
import todoApp from './reducers/reducers'

let store = createStore(todoApp)

let rootElement = document.getElementById('app')

render(

   <Provider store = {store}>
      <App />
   </Provider>,
	
   rootElement
)

Step 6 – Root Component

The App component is the root component of the app. Only root component should be aware of a redux. The important part to notice is the connectfunction which is used for connecting our root component App to the store. This function takes select function as an argument. The select function takes state from the store and returns the props (visibleTodos) that we can use in our components.

App.js

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addTodo } from './actions/actions'

import AddTodo from './components/AddTodo.jsx'
import TodoList from './components/TodoList.jsx'

class App extends Component {
   render() {
      const { dispatch, visibleTodos } = this.props
	
      return (
         <div>
			
            <AddTodo
               onAddClick = {text 
               dispatch(addTodo(text))}
            />
				
            <TodoList todos = {visibleTodos}/>
			
         </div>
      )
   }
}

function select(state) {
   return {
      visibleTodos: state.todos
   }
}

export default connect(select)(App)

Step 7 – Other Components

These components shouldn’t be aware of the redux.

components/AddTodo.js

import React, { Component, PropTypes } from 'react'

export default class AddTodo extends Component {
   render() {
      return (
         <div>
            <input type = 'text' ref = 'input' />
				
            <button onClick = {(e)  this.handleClick(e)}>
               Add
            </button>
				
         </div>
      )
   }

   handleClick(e) {
      const node = this.refs.input
      const text = node.value.trim()
      this.props.onAddClick(text)
      node.value = ''
   }
}

components/Todo.js

import React, { Component, PropTypes } from 'react'

export default class Todo extends Component {
   render() {
      return (
         <li>
            {this.props.text}
         </li>
      )
   }
}

components/TodoList.js

import React, { Component, PropTypes } from 'react'
import Todo from './Todo.jsx'

export default class TodoList extends Component {
   render() {
      return (
         <ul>
            {this.props.todos.map(todo 
               <Todo
               key = {todo.id}
               {...todo}
               />
            )}
         </ul>
      )
   }
}

When we start our app we will be able to add items to our list.

Reference:

https://www.tutorialspoint.com/reactjs/reactjs_using_flux.htm

https://facebook.github.io/flux/docs/overview.html#content

 

React Component Lifecycle

Introduction

React enables to create components by invoking the React.createClass() method which expects arender method and triggers a lifecycle that can be hooked into via a number of so called lifecycle methods.

This short article should shed light into all the applicable functions.

Understanding the component lifecycle will enable you to perform certain actions when a component is created or destroyed. Further more it gives you the opportunity to decide if a component should be updated in the first place and to react to props or state changes accordingly.

The Lifecycle

To get a clear idea of the lifecycle we will need to differentiate between the initial creation phase, where the component is created, and state and props changes triggered updates as well as the component unmoutings phase.

Initialization

Initialization Lifecycle

From looking at the image above we can see that the first two methods being called aregetDefaultProps and getInitialState. Both methods are only called once when initially rendering the component.

The getInitialState method enables to set the initial state value, that is accessible inside the component via this.state.

getInitialState: function(){
    return { /* something here */};
}

Analogously getDefaultProps can be used to define any default props which can be accessed viathis.props.

getDefaultProps: function(){
    return { /* something here */};
}

Another two methods that only get called when initializing a component are componentWillMountand componentDidMount.

componentWillMount is called before the render method is executed. It is important to note that setting the state in this phase will not trigger a re-rendering.

The render method returns the needed component markup, which can be a single child component or null or false (in case you don’t want any rendering).

This is the part of the lifecycle where props and state values are interpreted to create the correct output. Neither props nor state should should be modified inside this function. This is important to remember, as by definition the render function has to be pure, meaning that the same result is returned every time the method is invoked.

As soon as the render method has been executed the componentDidMount function is called. The DOM can be accessed in this method, enabling to define DOM manipulations or data fetching operations. Any DOM interactions should always happen in this phase not inside the render method.

State Changes

State changes will trigger a number of methods to hook into.

State Changes Lifecycle

shouldComponentUpdate is always called before the render method and enables to define if a re-rendering is needed or can be skipped. Obviously this method is never called on initial rendering. A boolean value must be returned.

shouldComponentUpdate: function(nextProps, nextState){
    // return a boolean value
    return true;
}

Access to the upcoming as well as the current props and state ensure that possible changes can be detected to determine if a rendering is needed or not.

componentWillUpdate gets called as soon as the the shouldComponentUpdate returned true. Any state changes via this.setState are not allowed as this method should be strictly used to prepare for an upcoming update not trigger an update itself.

componentWillUpdate: function(nextProps, nextState){
    // perform any preparations for an upcoming update
}

Finally componentDidUpdate is called after the render method. Similar to the componentDidMount, this method can be used to perform DOM operations after the data has been updated.

componentDidUpdate: function(prevProps, prevState){
    // 
}

Check the code example for more detailed insights.

Props Changes

Any changes on the props object will also trigger the lifecycle and is almost identical to the state change with one additional method being called.

Props Changes Lifecycle

componentWillReceiveProps is only called when the props have changed and when this is not an initial rendering. componentWillReceiveProps enables to update the state depending on the existing and upcoming props, without triggering another rendering. One interesting thing to remember here is that there is no equivalent method for the state as state changes should never trigger any props changes.

componentWillReceiveProps: function(nextProps) {
  this.setState({
    // set something 
  });
}

The rest of the lifecycle reveals nothing new here and is identical to the state change triggered cycle.

Unmounting

Unmount Lifecycle

The only method we haven’t touched yet is the componentWillUnmount which gets called before the component is removed from the DOM. This method can be beneficial when needing to perform clean up operations, f.e. removing any timers defined in componentDidMount.

Links

React Component Lifecycle Documentation

Hồng Môn Yến

  • Hạng Vũ: Sai lầm lớn nhất của Hạng Vũ có lẽ là không giết Lưu Bang hoặc Trương Lương. Trúng kế Trương Lương đuổi Á Phụ Phạm Tăng, giết chết Vua có lẽ chỉ là quả của sai lầm này. Người có chí lớn nhưng chỉ là 1 Lữ Bố.
  • Lưu Bang: Biết dùng người, biết thời thế, ẩn tướng làm Vua nhưng ko nên làm Vua.
  • Phạm Tăng: Giỏi, nhưng nước cờ cuối cùng vẫn thua Trương Lương.
  • Trương Lương: Cực giỏi. Ông nói Phạm Tăng hơn gấp 3 lần ông, nhưng thực sự ông hơn Phạm Tăng cái đầu.
  • Hàn Tín: Hữu dũng, nhưng quá thẳng và đòi lợi lộc. Có lẽ Lưu Bang trước sau gì cũng giết chết Hàn Tín cho dù không trúng kế Phạm Tăng.

 

Faster AngularJS Rendering (AngularJS and ReactJS)

Have you used AngularJs and ran into some performance problems? Using ReactJs rendering becomes much faster. A small examples explains how to use ReactJs for rendering in AngularJs and a comparison is made between native rendering and rendering using ReactJs.

I like AngularJS. I use it when I do some little fun projects and I use it professionally in large Web apps. I tried other frameworks as well, like BackboneJS and EmberJS, which both are great tools as well. All three of them belong to the class of MVC frameworks (or MVVC whatever you want o call them). But whenever I used any of such a tool I always ran and still run into the same problem: Rendering performance of lists of items. Two way binding or one-way binding makes no real difference. For me BackboneJS had better performance for rendering than AngularJS. Lets put that on the back of two-way binding.

Now there is this great tool coming along called ReactJS. And this little innocent looking lib will definitely make one of the biggest changes in JavaScript MVC frameworks for the last couple of months (if not years). In short words, this library will make rendering finally fast. ReactJs calls itself the V in MVC (the View). At first I was wondering, why the hell would I want to drop the MC part? The MC part is where the fun is in all these frameworks like EmberJs, BackboneJS and AngularJS, right? After a closer look, you can actually see that ReactJs has quite some features of the C (controller) part as well, but yet ReactJs is not a full featured MVC framework and does not intend to be. The way ReactJs works is to keep a virtual DOM and render only what actually changes when the UI is updated?? Does that make sense, sounds new but so true. Send command to update UI, React compares these changes to existing DOM (using the Virtual DOM for ultra-fast diff) and React only updates what is needed. The cool stuff is actually that the the diff of changes can be performed very fast on the Virtual DOM. Facebook and Instagram have developed ReactJs and are using it in production.

I listened to a podcast with Pete Hunt, dev of ReactJ, where this guy talks about the intention of ReactJs. To resume in this place, but be sure to listen to this podcast, the intentions behind open sourcing ReactJs are make some noise in the V part of existing frameworks. And I think that existing frameworks are going to adopt the same or similar strategy for their UI part, or new libraries will come up that can be used.

As ReactJs is the V it can be easily as V in existing frameworks already today. BackboneJS , more, with AngularJS, ngReact  orhere. Use it with Coffeescript? So you can use ReactJs to render those parts of your App where some performance comes in handy, for example ng-repeat with a few hundred items. In a previouspost, I blogged how to make long lists ‘usable’ in AngularJs, but all these techniques to make “rendering” faster all rely on rendering only a part of the list. Using ReactJs with AngularJs, your rendering time will drop by about 80%. I played with ngReact and I experienced a performance increase that made me think something was wrong. Rendering time dropped from about 4200ms in native AngularJs to 120ms using ReactJs.  Go check ngReact out to try it yourself, or have a look at the plunkrs in this post.

I still experienced some issues when there are too many bindings in the DOM with AngularJS, but this is another problem that is specific to two-way binding. If you are too scared of this problem, you should probably go with another framework than AngularJs. ReactJs just helps us getting things as fast as possible on he screen of the user and here ReactJs is making a great job.

I will show a small example on how to use ReactJs to render the view for an Angular app. I installed bower and then

user@computer:$ mkdir fast-angular

cd fast-angular

bower install –save react

bower install –save angular

And then we are good to go. We only need ReactJs and AngularJs. We create a simple html file with both scripts loaded:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

  </head>
  <body>
    <h1>Fast AngularJs</h1> <h3>AngularJs with ReactJs</h3>


    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/react/react.js"></script>

</body>
</html>

What we are going to create is a small ReactJs component that renders the string that we enter. So we use reactJs to render our model. We create a component called MYAPP, that renders a props that is passed to it. Then we create a traditional angularJs directive and controller (add the tags to our html, to start the app). The directive instead of rendering calls the ReactJs component and tells it to render. We use a $watch on framework to re-render on update. From the ReactJs docs calling createComponent when Component is already mounted updates the existing instance. (using React Chrome Dev integration tools, I keep on having the same instance ID, so I assume docs are true ) (See it live here http://plnkr.co/edit/FXK3lU?p=info)

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

  </head>
  <body ng-app="fasterAngular">
    <h1>Fast AngularJs</h1> <h3>AngularJs with ReactJs</h3>
    <div ng-controller="mycontroller">
        <input ng-model="framework"/>
        <hr>
        <fast-ng framework="framework"></fast-ng>
        <hr>
        Rendering with traditional AngularJs {{framework}}
    </div>

    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/react/react.js"></script>
    <script >
        var MYAPP = React.createClass({
            displayName:'MYAPP',
            render:function(){
                return React.DOM.div(null, "Rendering faster in AngularJs with ", this.props.framework);

            }
        });
    </script>

    <script>
        angular.module('fasterAngular', []).
        controller('mycontroller', ['$scope', function($scope){
            $scope.framework = 'ReactJs';
 
        }]).directive('fastNg', function(){
            return{
                restrict:'E',
                scope:{
                    framework:'='
                },
                link:function(scope, el, attrs){
                    scope.$watch('framework', function(newValue, oldValue){
                        React.renderComponent(
                            MYAPP({framework:newValue}),
                            el[0]
                        );
                    })
                }
            }
        })
    </script>
</body>
</html>

Of course this simple example does not make us gain some performance, but It illustrates how we can use ReactJs to render our model. An other example that shows the performance is the next one, where we render a long list of numbers. The example is taken from the example of ngReact. We generate an Array with 1500 data entries and render it in a table. This is usually what brings some performance problems with native ng-repeat in AngularJs. See this Plunkr for rendering using ReactJs (http://plnkr.co/edit/ykYILa) and this one for native ngRepeat rendering (http://plnkr.co/edit/YnF7Vn). See code here, rendering with ReactJs

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

  </head>
  <body ng-app="fasterAngular">
    <h1>Fast AngularJs</h1> <h3>AngularJs with ReactJs</h3>
    <div ng-controller="mycontroller">

        <fast-repeat data="data"></fast-repeat>

    </div>

    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/react/react.js"></script>

    <script >
        var MYLIST = React.createClass({displayName: 'MYLIST',
            render: function() {

              var data = this.props.data;

              var rows = data.map(function(datum) {
                var clickHandler = function(ev){
                    console.log("Still in reactJs");
                    console.log(ev);
                }

                return (
                  React.DOM.tr( {onClick:clickHandler},
                    React.DOM.td(null, datum['0']),
                    React.DOM.td(null, datum['1']),
                    React.DOM.td(null, datum['2']),
                    React.DOM.td(null, datum['3']),
                    React.DOM.td(null, datum['4'])
                  )
                );
              });

              return (
                React.DOM.table(null,
                  rows
                )
              );
            }
        });
    </script>
    <script>
        angular.module('fasterAngular', []).
        controller('mycontroller', ['$scope', function($scope){
            $scope.framework = 'ReactJs';
            $scope.data = [];
            // Fill the data map with random data
            for(var i = 0; i < 1500; ++i) {
                $scope.data[i] = {};
                for(var j = 0; j < 5; ++j) {
                    $scope.data[i][j] = Math.random();
                }
            }
        }]).directive('fastRepeat', function(){
            return{
                restrict: 'E',
                scope:{
                    data: '='
                },
                link:function(scope, el, attrs){
                    scope.$watch('data', function(newValue, oldValue){
                        React.renderComponent(
                            MYLIST({data:newValue}),
                            el[0]
                        );
                    })
                }
            }
        })
    </script>
</body>
</html>

A similar example where you can update the Data with a button Plunkr for Native Angular (http://plnkr.co/edit/YnF7Vn) and using ReactJs (http://plnkr.co/edit/6zfFXU)

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

  </head>
  <body ng-app="fasterAngular">
    <h1>Fast AngularJs</h1> <h3>AngularJs with ReactJs</h3>
    <div ng-controller="mycontroller">
        <button ng-click="refresh()">Refresh Data</button>
        <fast-repeat data="data"></fast-repeat>
        <!-- <table>
          <tr ng-repeat="line in data" ng-click="clickHandler(ev)">
            <td>{{line[0]}}</td>
            <td>{{line[1]}}</td>
            <td>{{line[2]}}</td>
            <td>{{line[3]}}</td>
            <td>{{line[4]}}</td>
          </tr>
        </table> -->
    </div>

    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/react/react.js"></script>

    <script >
        var MYLIST = React.createClass({displayName: 'MYLIST',
            render: function() {

              var data = this.props.data;

              var rows = data.map(function(datum) {
                var clickHandler = function(ev){
                    console.log("Still in reactJs");
                    console.log(ev);
                }

                return (
                  React.DOM.tr( {onClick:clickHandler},
                    React.DOM.td(null, datum['0']),
                    React.DOM.td(null, datum['1']),
                    React.DOM.td(null, datum['2']),
                    React.DOM.td(null, datum['3']),
                    React.DOM.td(null, datum['4'])
                  )
                );
              });

              return (
                React.DOM.table(null,
                  rows
                )
              );
            }
        });
    </script>
    <script>
        angular.module('fasterAngular', []).
        controller('mycontroller', ['$scope', function($scope){
            $scope.framework = 'ReactJs';
            $scope.data = [];
            // Fill the data map with random data

            $scope.clickHandler = function(){
                console.log("in AngularJS");
            }
            $scope.refresh = function(){
                for(var i = 0; i < 1500; ++i) {
                    $scope.data[i] = {};
                    for(var j = 0; j < 5; ++j) {
                        $scope.data[i][j] = Math.random();
                    }
                }
            }
            $scope.refresh()
        }]).directive('fastRepeat', function(){
            return{
                restrict: 'E',
                scope:{
                    data: '='
                },
                link:function(scope, el, attrs){
                    scope.$watchCollection('data', function(newValue, oldValue){
                        React.renderComponent(
                            MYLIST({data:newValue}),
                            el[0]
                        );
                    })
                }
            }
        })
    </script>
</body>
</html>

To render 1500 rows, with AngularJS the time to render was about 1.35 seconds. When we let ReactJs do the rendering time was about 310ms. I attached the timeline for both from Chrome Dev Tools

 

Rendering with ReactJs, 320ms

Rendering with ReactJs, 320ms

Native AngularJs rendering 1200ms

Native AngularJs rendering 1200ms

This is just a short introduction to use ReactJs with AngularJs. For some parts of my next apps I will definitely use ReactJs to render parts of it where I think that performance will be an issue. ReactJs, as said by Pete Hunt,  is quite a game changer and the intentions behind is to show the general idea of its internal workings. I assume all major frameworks will soon have a similar concept that will be used with them or something to integrate easily. I like ReactJs and the idea behind to use a virtual DOM for the diff makes perfect sense.

In a coming up post I will write about communication between ReactJs and AngularJs, follow me on twitter to stay tuned. I am just playing around…if you think I made some terrible mistakes, ignore best practices, break stuff…etc please comment or write me and I will happily learn and update this post.

 

UPDATE 21.04.2014 21:00 CET: This post was creating some discussions and I got a bigger response than expected. Some people gave good feedback and other ideas to explore. Others questioned the usefulness of combining ReactJs with AngularJs. I try to explore the constructive feedback given and leave the more subjective response to everyone to figure it out. Find the discussion here: Hackernews,  and Reddit.

* The argument that the loaf of another JS file does not value the performance increase, did not maybe see that this performance helps increasing responsiveness of the app and therefore increase usability. And not only on initial call be on every update. For me I have been spending ours to make WebApps react faster on user input. Webapps already have a great difficulty to deal with (300ms delay). For me I will to a reasonable amount always choose what helps usability.

* The first hint was to use track by $index in the ng-repeat directive (“…With this association in place, AngularJS will not $destroy and re-create DOM nodes unnecessarily. This can have a huge performance and user experience benefit….” read here about it, and official docs) As far as I understood track by $index, this will only render faster when DOM is updated, but not on INITIAL rendering. So I tested again using the same example as above, let the test run several times and found the following results

  1. AngularJs + ReactJs: (http://plnkr.co/edit/6zfFXU?p=preview) Initial loading: ~ 243ms, Updating: ~ 125ms
  2. AngularJS using Track By (http://plnkr.co/edit/5FCsQO?p=preview) Initial loading: ~ 990ms, Updating: ~130ms
  3. AngularJs ngRepeat (http://plnkr.co/edit/YnF7Vn?p=preview) Initial loading: ~ 1100ms, Updating: 1150ms

So Track By $index does really have a huge impact when model is updated. (jn plunkrs hit refresh button in HTML), but initial rendering is still slow. I tried to run the tests several time and times may vary a little but the trend never changed. See timelines here:

AngularJs with ReactJs Updating

AngularJs with ReactJs Updating

AngularJs with ReactJs Initial Load

AngularJs with ReactJs Initial Load

Straight AngularJs. Updating

Straight AngularJs. Updating

Straight AngularJs Initial Load

Straight AngularJs Initial Load

AngularJs using Track By. Updating.

AngularJs using Track By. Updating.

AngularJs using Track By Initial Loading

AngularJs using Track By Initial Loading


* Virtual DOM in AngularJS: Ahmed pointed out in the comments (down here) the point of view of AngularJS Team on Virtual DOM.  http://www.youtube.com/watch?v=srt3OBP2kGc#t=118 As I think too, making the diff on a virtual DOM is what sooner or later will be done by default either in Browsers or frameworks. As Pete Hunt stated in the podcast linked above, that was the intentions of ReactJs’ Team

* BindOnce? I don’t think that https://github.com/Pasvaz/bindonce has anything to do here with the performance of rendering. The performance that is gained is a different one, when there are too many bindings any updates becomes slow, scrolling is lagging..etc. Here it is just writing and updating the DOM. Please comment me if you think I am wrong, or provide examples.

* Rendering using Mustache or Handlebars (In comments): I tried the plunkr and yes, rendering the DOM (initial and updating) is fast. Initial load ~ 220ms and updating is even faster ~ 120ms. That is also impressive numbers. This is even faster than with ReactJs. But I think that something goes lost here. In the examples there is always a click handler on the rows that renders to the console. Is this possible with Mustache or Handlebars? I am still working on an example to get the communication between AngularJs and ReactJs going, and I guess this is not possible with a template lib like Mustache or Handlebars. But be assured Mustache is rendering fast and I will keep it in mind for future work.

* Mithril, seems to be a new framework on the market. I know I already came across the framework once, but it seems to be rendering fast. Also using a virtual DOM. Difficult to tell which direction this framework will take? But the works seems interesting and I will check into the code to see what is so different from ReactJs virtual Dom.

Looking forward to more feedback. AngularJs 2.0 is on the way and I don’t know whtas coming, but I really appreciate the way the folks at Google have chosen to develop the framework by including the community.

Reference:

http://www.williambrownstreet.net/blog/2014/04/faster-angularjs-rendering-angularjs-and-reactjs/

https://www.quora.com/profile/Pete-Hunt/Posts/Facebooks-React-vs-AngularJS-A-Closer-Look

Bài thơ tặng vợ tháng 10/2013

Lần đầu tiên mình gặp cô ấy vào buổi lễ giáng sinh được công ty tổ chức năm 2012. Cô ấy là MC chương trình, còn mình là 1 anh chàng dev say bia, say mồi và say MC chẳng quen kia. Cuối buổi lễ Giáng Sinh mình cùng mấy người bạn ngồi lại với nhau để say bia, say đàn, say thêm tiếng hát, đương nhiên có cả cô MC xinh đẹp ấy. Mình đàn, cô ấy hát. Tàn tiệc chia tay trong lưu luyến. Cô ấy được anh chàng cùng công ty chở về, đương nhiên mình có đứng ra đề nghị mình sẽ đưa cô ấy về, nhưng lần gặp đầu tiên cô ấy còn xa lạ.

Mấy ngày sau nhờ người chị PM tên D, chị nói mình theo đuổi cô gái ấy đi, vì anh chàng kia lăng nhăng quá, quen nhiều cô cùng lúc. Nói thế thôi, chứ mình nghĩ chỉ là cuộc gặp gỡ thoáng qua, kỷ niệm đẹp.

Thế là thời gian trôi qua, mình và cô ấy không gặp cũng không liên lạc mãi cho đến 1 hôm farewell chị PM D xinh đẹp ấy. Mình hỏi vui với chị D: “có rủ nàng MC hôm nọ không, hôm bữa mình và nàng ấy đàn hát, giờ lưu luyến quá”, thế rồi chị D copy đoạn chat cho cô nàng MC. Nàng MC add skype mình và bắt đầu những dòng trò chuyện đầu tiên.

Thế đấy, lần gặp lại này đã gần tròn 1 năm rồi, ngày sinh nhật cô ấy. Đây là bài thơ mình tặng cô ấy sau 1 thời gian dài hội ngộ:

Nhớ lại hôm nào nơi chốn đông,

Gặp em cô gái nhỏ má hồng,

Vô tư em ngắm vầng trăng ấy,

Lặng lẽ tôi nhìn mãi ngóng trông.

 

Hôm nay, gặp lại má vẫn hồng.

Vẫn nụ cười ấy, vẫn hoài mong.

Tiếng đàn ai dạo lời tha thiết,

Tiếng hát em hòa có nhớ không.

 

 

 

7 bước làm tăng tốc độ Google nhận biết website của bạn

Hầu hết những chuyên gia SEO đều khuyên bạn nên mua 1 site domain đã cũ để được Google đánh giá cao hơn và dễ Index hơn, nhưng nếu như bạn bắt đầu tạo 1 website mới thì sao? Thường thì bạn sẽ tốn vài tuần để site của bạn được bộ máy tìm kiếm google biết đến.Tuy nhiên những việc làm theo những bước sau đây sẻ giúp bạn tiết kiệm khá nhiều thời gian cho việc index site (chỉ sau khoảng 24h).

1/ Tạo 5 trang nội dung trong site:

Đừng để site bạn “under construction” (site đang trong quá trình xây dựng) hãy tạo 1 vài trang với nội dung thật sự.

2/ Tạo link nội bộ giữa các trang của bạn:

Hãy sử dụng template thống nhất để quản lý các trang nội dung thông qua các menu. Bạn có thể tìm thấy những template free giúp bạn làm việc này tại freecodevn.com hoặc joomlaviet.org…. Nếu bạn tự tạo thì nhớ hãy đơn giản hóa nó chứ đừng có làm nó quá phức tạp và cầu kỳ. Bạn nhớ liên kết 2, 3 trang (liên kết có chiều sâu)

3/ Đưa trang web của bạn lên các Social Bookmark Sites:

Bạn chỉ mất vài phút để tạo tài khoản và đăng trang web của bạn lên các bookmark site này. Việc làm này giúp các bộ máy tìm kiếm liên kết tìm kiếm trang web của bạn có cách dễ dàng hơn. Các bookmark sites thông dụng là: Del.icio.us, BlinkList, StumbleUpon.com, và Furl. Bạn lưu ý rằng khi ghi vào phần Tag, nhớ ghi những Tag thông dụng và phổ biến.

4/ Đăng trang web của bạn trên những blog phổ biến (nhớ kèm theo link):

Bạn tìm khoảng 5 trang blog phổ biến, và có những bài viết vừa mới viết,thường xuyên . Bạn cố gắng vào đó comment, xây dựng câu truyện và kèm theo link đến trang web của bạn.

5/ Tạo, đưa lên và ping XML Sitemap:

Bạn có thể tạo 1 trang xml free (tìm hiểu làm sitemap cho website) sau đó bạn đưa trang này lên website của bạn sau đó thì ping nó với google bằng link sau: http://google.com/webmasters/sitemaps/ping?sitemap=XXXX (đổi XXX thành link Sitemap trang web của bạn) Sau đó bạn tạo tài khoản Google Webmaster Central, và đưa lên Google XML Sitemap. Một số mã nguồn mở thường có plugin hoặc component để tự tạo google sitemap tự cập nhật cho website như xmap của joomla và google sitemap generator của wordpress…

6/ Cài đặt Google Analytics:

Cài đặt Google Analytics lên site của bạn và bạn nhớ là xác nhận lại thông tin của GA cho phù hợp với site của bạn.

7/ Tạo 1 số quảng cáo của Google:

Tạo tài khoản Google Adwords và add 1 số quảng cáo vào site của bạn. Bạn cứ add thậm chí chỉ là domain hay tên công ty thôi, không cần quan tâm nhiều đến keyword. Bởi vì khi add thì chắc chắn google sẽ phải ghé thăm site của bạn. Chỉ cần tốn 1 ít tiền thì site của bạn đã có rất nhiều lợi ích.

Với việc bạn làm theo các bước này bạn sẽ thấy rằng site của bạn sẽ rất nhanh chóng được phổ biến rộng rải. Mình không chắc chắn trong 24h bạn sẽ thành công, nhưng điều đó là có thể. Cách làm này chắc chắn sẽ rút ngắn thời gian index site từ vài tuần xuống chỉ còn vài ngày

Theo VietSEO.net

Tạo trang tin tức 30′ với wordpress

Để tạo trang tin tức động đẹp, nhiều widget hỗ trợ, dể dàng sử dụng với chi phí thấp và thời gian nhanh, bạn không nên bỏ qua

colorMag

Nhiệm vụ còn lại của bạn là upload resource, makup layout, chia category, viết bài, phân loại bài viết. 🙂

Tạo website cá nhân chỉ tốn tiền domain

blog_wordpress

Tạo 1 blog hoặc website cá nhân với chi phí rẻ, chỉ tốn duy nhất tiền domain (free nếu dùng subdomain). Tại sao bạn không thử!

  • Việc đầu tiên bạn làm là chọn cho mình 1 domain ưng ý. Bạn có thể mua tại godaddy với giá 184k/1 năm với domain .com. Hoặc bạn có thể dùng subdomain ở các trang web cung cấp free.
  • Vào hostinger đăng ký 1 hosting free ứng với domain bạn đã mua.
  • Download wordpress framework tại wordpress và upload lên hostinger.
  • Cài đặt wordpress với mySQL miễn phí trên hostinger.
  • Chọn theme, config giao diện.

Thế là xong, bạn có ngay 1 website với domain .com của riêng bạn. Bạn có thể viết bài, đăng bài, toàn quyền bằng quyền Administrator.