Stay Hungry,Stay Foolish!

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
复制代码

 

posted @   lightsong  阅读(586)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
千山鸟飞绝,万径人踪灭
点击右上角即可分享
微信分享提示