• ReactiveX编程范式


    ReactiveX

    http://reactivex.io/

    An API for asynchronous programming
    with observable streams

    The Observer pattern done right

    ReactiveX is a combination of the best ideas from
    the Observer pattern, the Iterator pattern, and functional programming

    Easily create event streams or data streams.
    Compose and transform streams with query-like operators.
    Subscribe to any observable stream to perform side effects.
     
     
    http://reactivex.io/intro.html

    ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences.

    It extends the observer pattern to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O.

    The ReactiveX Observable model allows you to treat streams of asynchronous events with the same sort of simple, composable operations that you use for collections of data items like arrays. It frees you from tangled webs of callbacks, and thereby makes your code more readable and less prone to bugs.

    http://reactivex.io/documentation/observable.html

    In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so.

    ReactiveX中文

    https://segmentfault.com/a/1190000003632186

    响应式编程是一种面向数据流和变化传播的编程范式,数据更新是相关联的。比如很多时候,在写界面的时候,我们需要对事件做处理,伴随着前端事件的增多,对于事件的处理愈发需要更加方便的处理。

    设想一下,平时在处理事件的时候,一单上了复杂度,比如输入的时候,需要停止输入的时候才进行,这个时候又只能输入长度大于2才进行事件,当还是之前的数据的话不进行事件,可以考虑一下这个情况下如何去写。

    例子

    var keyup = Rx.Observable.fromEvent($input, 'keyup')
          .map(function (e) {
            return e.target.value; 
          })
          .filter(function (text) {
            return text.length > 2; 
          })
          .debounce(750)
          .distinctUntilChanged(); 

    三秒后解除

    var btn = document.getElementById('button');
    var logRun = Rx.Observable.fromEvent(btn, 'click')
                 .merge(Rx.Observable.timer(3000))
                 .subscribe(e => {
                   console.log('run!');
                   logRun.dispose(); // 如果是一次性的就移除observable
                 });

    ReactJS语言实现

    https://github.com/Reactive-Extensions/RxJS

    例子如上。

    教程!!

    http://xgrommx.github.io/rx-book/why_rx.html

    为什么要使用 ReactJS, 因为 其将 Promise 和 DOM 作为一个整体对待。

    One question you may ask yourself, is why RxJS? What about Promises? Promises are good for solving asynchronous operations such as querying a service with an XMLHttpRequest, where the expected behavior is one value and then completion. The Reactive Extensions for JavaScript unifies both the world of Promises, callbacks as well as evented data such as DOM Input, Web Workers, Web Sockets. Once we have unified these concepts, this enables rich composition.

    ReactLua语言实现

    https://github.com/bjornbytes/RxLua

    Reactive Extensions for Lua.

    RxLua gives Lua the power of Observables, which are data structures that represent a stream of values that arrive over time. They're very handy when dealing with events, streams of data, asynchronous requests, and concurrency.

    local Rx = require 'rx'
    
    Rx.Observable.fromRange(1, 8)
      :filter(function(x) return x % 2 == 0 end)
      :concat(Rx.Observable.of('who do we appreciate'))
      :map(function(value) return value .. '!' end)
      :subscribe(print)
    
    -- => 2! 4! 6! 8! who do we appreciate!

    协程异步。

    local Rx = require 'rx'
    local scheduler = Rx.CooperativeScheduler.create()
    
    -- Cheer someone on using functional reactive programming
    
    local observable = Rx.Observable.fromCoroutine(function()
      for i = 2, 8, 2 do
        coroutine.yield(i)
      end
    
      return 'who do we appreciate'
    end, scheduler)
    
    observable
      :map(function(value) return value .. '!' end)
      :subscribe(print)
    
    repeat
      scheduler:update()
    until scheduler:isEmpty()

    最简洁

    local Rx = require 'rx'
    
    -- Create an observable that produces a single value and print it.
    Rx.Observable.of(42):subscribe(print)

    concat例子

    local Rx = require 'rx'
    
    local first = Rx.Observable.fromRange(3)
    local second = Rx.Observable.fromRange(4, 6)
    local third = Rx.Observable.fromRange(7, 11, 2)
    
    first:concat(second, third):dump('concat')
    
    print('Equivalent to:')
    
    
    Rx.Observable.concat(first, second, third):dump('concat')

    观察者模式

    local Rx = require 'rx'
    
    local subject = Rx.Subject.create()
    
    subject:subscribe(function(x)
      print('observer a ' .. x)
    end)
    
    subject:subscribe(function(x)
      print('observer b ' .. x)
    end)
    
    subject:onNext(1)
    subject(2)
    subject:onNext(3)

    多道并发

    local Rx = require 'rx'
    local scheduler = Rx.CooperativeScheduler.create()
    local timerResolution = .25
    local function log(message)
      print('[' .. string.format('%.2f', scheduler.currentTime) .. '] ' .. message)
    end
    
    -- Demonstrate Rx.Scheduler.Cooperative by running some simultaneous cooperative threads.
    scheduler:schedule(function()
      log('this is like a setTimeout')
    end, 2)
    
    scheduler:schedule(function()
      local i = 1
      while true do
        log('this prints i twice per second: ' .. i)
        i = i + 1
        coroutine.yield(.5)
      end
    end)
    
    scheduler:schedule(function()
      for i = 1, 3 do
        log('this will print for 3 updates after 1 second')
        coroutine.yield()
      end
    end, 1)
    
    -- Simulate 3 virtual seconds.
    repeat
      scheduler:update(timerResolution)
    until scheduler.currentTime >= 3
  • 相关阅读:
    tp框架自带扩展分页类修改样式
    win7获取管理员权限
    Git学习手记(二)
    安卓导出安装包
    浅谈存储过程
    Java宝典
    单例设计模式
    关于Cookie的有关内容
    开辟html5和css3学习随笔(2015-3-2)
    关于面试题
  • 原文地址:https://www.cnblogs.com/lightsong/p/6247034.html
Copyright © 2020-2023  润新知