Shuhei Kagawa

Incremental search with RxJS switchMap

@2016-05-02 02:18 - JavaScript, RxJS

RxJS leads us to better design separating data flow and side-effects. In addition, it provides powerful functionalities that sophisticate the outcome application. My favorite is switchMap of RxJS 5, which is equivalent to flatMapLatest in RxJS 4.


switchMap(func) is equivalent to map(func).switch(). It keeps subscribing latest observable at the moment and unsubscribing outdated ones so that it only streams events from latest observable at the moment. Take a look at the marble chart for switch. It illustrates the behavior well.

switchMap is convenient for properly implementing incremental search. Incremental search makes multiple requests to a server. The server can respond in a different order from requests'. Because of the order, a naive implementation may show a wrong result. However, you can effortlessly avoid the caveat if you use switchMap.

Here is an example. Type fast in the text fields. Without switchMap sometimes shows a wrong result while With switchMap always works fine.

JS Bin on

search function mocks an AJAX request. It returns a Promise that resolves after a random delay.

function search(keyword) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Result of ' + keyword);
    }, Math.random() * 1000);

A naive implementation always shows the last response at the time. A wrong result is shown if responses come in a different order from requests'. We could add some debouncing to decrease the chance of the wrong order but it still may happen when response time is longer than the debounce time.

const keyword = document.getElementById('keyword-without');
const result = document.getElementById('result-without');

keyword.addEventListener('keyup', e => {
  const value =;
    .then(data => result.textContent = data);

switchMap guarantees that the last keyword's result is finally shown.

const keyword = document.getElementById('keyword-with');
const result = document.getElementById('result-with');

const keyword$ = Rx.Observable.fromEvent(keyword, 'keyup')
  .map(e =>;
  .subscribe(data => result.textContent = data);

Clean up before exiting in Haskell

@2016-04-06 00:32 - Haskell

Once upon a time (or a several days ago), I was reading Programming in Haskell. When I ran 9.7's Game of Life, which shows Game of Life animation on the terminal, the terminal's cursor was flickering and annoying. So I tried to hide it when starting and show when exiting.

import System.Process (system)

main :: IO ()
main = do
  -- Hide the cursor
  system "tput civis"
  -- Show the Game of Life
  life glider
  -- Show the cursor (but the code does not reach here!)
  system "tput cvvis"
  return ()

life :: Board -> IO ()
glider :: Board

But the code does not reach the line that shows the cursor because life is a infinite loop. If I quit the program with Ctrl+C, the cursor remains hidden.

So I wrote a function that loops a -> IO a until interrupted by a signal, referring to unix - Killing a Haskell binary - Stack Overflow. It manages a state of whether the program was interrupted in a MVar and stops the loop when interrupted.

import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, tryTakeMVar)
import System.Posix.Signals (Handler, Handler(CatchOnce), installHandler, sigINT, sigTERM)

loopUntilInterruption :: (a -> IO a) -> a -> IO ()
loopUntilInterruption p init = do
  v <- newEmptyMVar
  installHandler sigINT (handler v) Nothing
  installHandler sigTERM (handler v) Nothing
  loop v p init

handler :: MVar () -> Handler
handler v = CatchOnce $ putMVar v ()

loop :: MVar () -> (a -> IO a) -> a -> IO ()
loop v p prev = do
  x <- p prev
  val <- tryTakeMVar v
  case val of
    Just _ -> return ()
    Nothing -> loop v p x >> return ()

In the Game of Life, I changed the type of life so that it returns the result of its previous result and loop with loop. Now the clean up code will be called when interrupted by a signal.

import System.Process (system)

main :: IO ()
main = do
  -- Hide the cursor
  system "tput civis"
  -- Loop until interrupted
  loopUntilInterruption life glider
  -- Show the cursor (the code will reach here now!)
  system "tput cvvis"
  return ()

life :: Board -> IO Board
glider :: Board

And they lived happily ever after.

One-time binding for ng-if

@2016-04-05 23:58 - JavaScript, AngularJS

AngularJS's one-time binding is useful to reduce the number of watches. It stops watching its expression once it becomes defined. It kindly keeps watching while the value is undefined for cases like asynchronous data fetching. But the kindness can be a pitfall especially for directives that take boolean expressions like ng-if.

Here's an ordinary piece of AngularJS template. It shows 'Something' when obj.prop exists.

<div ng-if="::obj.prop">Something</div>

It works almost fine. But it keeps watching the expression when the message is hidden. Guess what?

Yes! It keeps watching while the expression is undefined. Let's make sure that it's always boolean.

<div ng-if="::!!obj.prop">Something</div>

Here we see the birth of a new operator ::!!!