rx.all.js 428 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388
  1. // Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
  2. ;(function (undefined) {
  3. var objectTypes = {
  4. 'function': true,
  5. 'object': true
  6. };
  7. function checkGlobal(value) {
  8. return (value && value.Object === Object) ? value : null;
  9. }
  10. var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
  11. var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
  12. var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
  13. var freeSelf = checkGlobal(objectTypes[typeof self] && self);
  14. var freeWindow = checkGlobal(objectTypes[typeof window] && window);
  15. var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
  16. var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
  17. var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
  18. var Rx = {
  19. internals: {},
  20. config: {
  21. Promise: root.Promise
  22. },
  23. helpers: { }
  24. };
  25. // Defaults
  26. var noop = Rx.helpers.noop = function () { },
  27. identity = Rx.helpers.identity = function (x) { return x; },
  28. defaultNow = Rx.helpers.defaultNow = Date.now,
  29. defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
  30. defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
  31. defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
  32. defaultError = Rx.helpers.defaultError = function (err) { throw err; },
  33. isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; },
  34. isFunction = Rx.helpers.isFunction = (function () {
  35. var isFn = function (value) {
  36. return typeof value == 'function' || false;
  37. };
  38. // fallback for older versions of Chrome and Safari
  39. if (isFn(/x/)) {
  40. isFn = function(value) {
  41. return typeof value == 'function' && toString.call(value) == '[object Function]';
  42. };
  43. }
  44. return isFn;
  45. }());
  46. function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
  47. var errorObj = {e: {}};
  48. function tryCatcherGen(tryCatchTarget) {
  49. return function tryCatcher() {
  50. try {
  51. return tryCatchTarget.apply(this, arguments);
  52. } catch (e) {
  53. errorObj.e = e;
  54. return errorObj;
  55. }
  56. };
  57. }
  58. var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
  59. if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
  60. return tryCatcherGen(fn);
  61. };
  62. function thrower(e) {
  63. throw e;
  64. }
  65. Rx.config.longStackSupport = false;
  66. var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })();
  67. hasStacks = !!stacks.e && !!stacks.e.stack;
  68. // All code after this point will be filtered from stack traces reported by RxJS
  69. var rStartingLine = captureLine(), rFileName;
  70. var STACK_JUMP_SEPARATOR = 'From previous event:';
  71. function makeStackTraceLong(error, observable) {
  72. // If possible, transform the error stack trace by removing Node and RxJS
  73. // cruft, then concatenating with the stack trace of `observable`.
  74. if (hasStacks &&
  75. observable.stack &&
  76. typeof error === 'object' &&
  77. error !== null &&
  78. error.stack &&
  79. error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
  80. ) {
  81. var stacks = [];
  82. for (var o = observable; !!o; o = o.source) {
  83. if (o.stack) {
  84. stacks.unshift(o.stack);
  85. }
  86. }
  87. stacks.unshift(error.stack);
  88. var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n');
  89. error.stack = filterStackString(concatedStacks);
  90. }
  91. }
  92. function filterStackString(stackString) {
  93. var lines = stackString.split('\n'), desiredLines = [];
  94. for (var i = 0, len = lines.length; i < len; i++) {
  95. var line = lines[i];
  96. if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
  97. desiredLines.push(line);
  98. }
  99. }
  100. return desiredLines.join('\n');
  101. }
  102. function isInternalFrame(stackLine) {
  103. var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
  104. if (!fileNameAndLineNumber) {
  105. return false;
  106. }
  107. var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
  108. return fileName === rFileName &&
  109. lineNumber >= rStartingLine &&
  110. lineNumber <= rEndingLine;
  111. }
  112. function isNodeFrame(stackLine) {
  113. return stackLine.indexOf('(module.js:') !== -1 ||
  114. stackLine.indexOf('(node.js:') !== -1;
  115. }
  116. function captureLine() {
  117. if (!hasStacks) { return; }
  118. try {
  119. throw new Error();
  120. } catch (e) {
  121. var lines = e.stack.split('\n');
  122. var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2];
  123. var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
  124. if (!fileNameAndLineNumber) { return; }
  125. rFileName = fileNameAndLineNumber[0];
  126. return fileNameAndLineNumber[1];
  127. }
  128. }
  129. function getFileNameAndLineNumber(stackLine) {
  130. // Named functions: 'at functionName (filename:lineNumber:columnNumber)'
  131. var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
  132. if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
  133. // Anonymous functions: 'at filename:lineNumber:columnNumber'
  134. var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
  135. if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
  136. // Firefox style: 'function@filename:lineNumber or @filename:lineNumber'
  137. var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
  138. if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
  139. }
  140. var EmptyError = Rx.EmptyError = function() {
  141. this.message = 'Sequence contains no elements.';
  142. Error.call(this);
  143. };
  144. EmptyError.prototype = Object.create(Error.prototype);
  145. EmptyError.prototype.name = 'EmptyError';
  146. var ObjectDisposedError = Rx.ObjectDisposedError = function() {
  147. this.message = 'Object has been disposed';
  148. Error.call(this);
  149. };
  150. ObjectDisposedError.prototype = Object.create(Error.prototype);
  151. ObjectDisposedError.prototype.name = 'ObjectDisposedError';
  152. var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
  153. this.message = 'Argument out of range';
  154. Error.call(this);
  155. };
  156. ArgumentOutOfRangeError.prototype = Object.create(Error.prototype);
  157. ArgumentOutOfRangeError.prototype.name = 'ArgumentOutOfRangeError';
  158. var NotSupportedError = Rx.NotSupportedError = function (message) {
  159. this.message = message || 'This operation is not supported';
  160. Error.call(this);
  161. };
  162. NotSupportedError.prototype = Object.create(Error.prototype);
  163. NotSupportedError.prototype.name = 'NotSupportedError';
  164. var NotImplementedError = Rx.NotImplementedError = function (message) {
  165. this.message = message || 'This operation is not implemented';
  166. Error.call(this);
  167. };
  168. NotImplementedError.prototype = Object.create(Error.prototype);
  169. NotImplementedError.prototype.name = 'NotImplementedError';
  170. var notImplemented = Rx.helpers.notImplemented = function () {
  171. throw new NotImplementedError();
  172. };
  173. var notSupported = Rx.helpers.notSupported = function () {
  174. throw new NotSupportedError();
  175. };
  176. // Shim in iterator support
  177. var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
  178. '_es6shim_iterator_';
  179. // Bug for mozilla version
  180. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
  181. $iterator$ = '@@iterator';
  182. }
  183. var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
  184. var isIterable = Rx.helpers.isIterable = function (o) {
  185. return o && o[$iterator$] !== undefined;
  186. };
  187. var isArrayLike = Rx.helpers.isArrayLike = function (o) {
  188. return o && o.length !== undefined;
  189. };
  190. Rx.helpers.iterator = $iterator$;
  191. var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
  192. if (typeof thisArg === 'undefined') { return func; }
  193. switch(argCount) {
  194. case 0:
  195. return function() {
  196. return func.call(thisArg)
  197. };
  198. case 1:
  199. return function(arg) {
  200. return func.call(thisArg, arg);
  201. };
  202. case 2:
  203. return function(value, index) {
  204. return func.call(thisArg, value, index);
  205. };
  206. case 3:
  207. return function(value, index, collection) {
  208. return func.call(thisArg, value, index, collection);
  209. };
  210. }
  211. return function() {
  212. return func.apply(thisArg, arguments);
  213. };
  214. };
  215. /** Used to determine if values are of the language type Object */
  216. var dontEnums = ['toString',
  217. 'toLocaleString',
  218. 'valueOf',
  219. 'hasOwnProperty',
  220. 'isPrototypeOf',
  221. 'propertyIsEnumerable',
  222. 'constructor'],
  223. dontEnumsLength = dontEnums.length;
  224. var argsTag = '[object Arguments]',
  225. arrayTag = '[object Array]',
  226. boolTag = '[object Boolean]',
  227. dateTag = '[object Date]',
  228. errorTag = '[object Error]',
  229. funcTag = '[object Function]',
  230. mapTag = '[object Map]',
  231. numberTag = '[object Number]',
  232. objectTag = '[object Object]',
  233. regexpTag = '[object RegExp]',
  234. setTag = '[object Set]',
  235. stringTag = '[object String]',
  236. weakMapTag = '[object WeakMap]';
  237. var arrayBufferTag = '[object ArrayBuffer]',
  238. float32Tag = '[object Float32Array]',
  239. float64Tag = '[object Float64Array]',
  240. int8Tag = '[object Int8Array]',
  241. int16Tag = '[object Int16Array]',
  242. int32Tag = '[object Int32Array]',
  243. uint8Tag = '[object Uint8Array]',
  244. uint8ClampedTag = '[object Uint8ClampedArray]',
  245. uint16Tag = '[object Uint16Array]',
  246. uint32Tag = '[object Uint32Array]';
  247. var typedArrayTags = {};
  248. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  249. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  250. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  251. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  252. typedArrayTags[uint32Tag] = true;
  253. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  254. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  255. typedArrayTags[dateTag] = typedArrayTags[errorTag] =
  256. typedArrayTags[funcTag] = typedArrayTags[mapTag] =
  257. typedArrayTags[numberTag] = typedArrayTags[objectTag] =
  258. typedArrayTags[regexpTag] = typedArrayTags[setTag] =
  259. typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
  260. var objectProto = Object.prototype,
  261. hasOwnProperty = objectProto.hasOwnProperty,
  262. objToString = objectProto.toString,
  263. MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
  264. var keys = Object.keys || (function() {
  265. var hasOwnProperty = Object.prototype.hasOwnProperty,
  266. hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
  267. dontEnums = [
  268. 'toString',
  269. 'toLocaleString',
  270. 'valueOf',
  271. 'hasOwnProperty',
  272. 'isPrototypeOf',
  273. 'propertyIsEnumerable',
  274. 'constructor'
  275. ],
  276. dontEnumsLength = dontEnums.length;
  277. return function(obj) {
  278. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  279. throw new TypeError('Object.keys called on non-object');
  280. }
  281. var result = [], prop, i;
  282. for (prop in obj) {
  283. if (hasOwnProperty.call(obj, prop)) {
  284. result.push(prop);
  285. }
  286. }
  287. if (hasDontEnumBug) {
  288. for (i = 0; i < dontEnumsLength; i++) {
  289. if (hasOwnProperty.call(obj, dontEnums[i])) {
  290. result.push(dontEnums[i]);
  291. }
  292. }
  293. }
  294. return result;
  295. };
  296. }());
  297. function equalObjects(object, other, equalFunc, isLoose, stackA, stackB) {
  298. var objProps = keys(object),
  299. objLength = objProps.length,
  300. othProps = keys(other),
  301. othLength = othProps.length;
  302. if (objLength !== othLength && !isLoose) {
  303. return false;
  304. }
  305. var index = objLength, key;
  306. while (index--) {
  307. key = objProps[index];
  308. if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
  309. return false;
  310. }
  311. }
  312. var skipCtor = isLoose;
  313. while (++index < objLength) {
  314. key = objProps[index];
  315. var objValue = object[key],
  316. othValue = other[key],
  317. result;
  318. if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) {
  319. return false;
  320. }
  321. skipCtor || (skipCtor = key === 'constructor');
  322. }
  323. if (!skipCtor) {
  324. var objCtor = object.constructor,
  325. othCtor = other.constructor;
  326. if (objCtor !== othCtor &&
  327. ('constructor' in object && 'constructor' in other) &&
  328. !(typeof objCtor === 'function' && objCtor instanceof objCtor &&
  329. typeof othCtor === 'function' && othCtor instanceof othCtor)) {
  330. return false;
  331. }
  332. }
  333. return true;
  334. }
  335. function equalByTag(object, other, tag) {
  336. switch (tag) {
  337. case boolTag:
  338. case dateTag:
  339. return +object === +other;
  340. case errorTag:
  341. return object.name === other.name && object.message === other.message;
  342. case numberTag:
  343. return (object !== +object) ?
  344. other !== +other :
  345. object === +other;
  346. case regexpTag:
  347. case stringTag:
  348. return object === (other + '');
  349. }
  350. return false;
  351. }
  352. var isObject = Rx.internals.isObject = function(value) {
  353. var type = typeof value;
  354. return !!value && (type === 'object' || type === 'function');
  355. };
  356. function isObjectLike(value) {
  357. return !!value && typeof value === 'object';
  358. }
  359. function isLength(value) {
  360. return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
  361. }
  362. var isHostObject = (function() {
  363. try {
  364. Object({ 'toString': 0 } + '');
  365. } catch(e) {
  366. return function() { return false; };
  367. }
  368. return function(value) {
  369. return typeof value.toString !== 'function' && typeof (value + '') === 'string';
  370. };
  371. }());
  372. function isTypedArray(value) {
  373. return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
  374. }
  375. var isArray = Array.isArray || function(value) {
  376. return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag;
  377. };
  378. function arraySome (array, predicate) {
  379. var index = -1,
  380. length = array.length;
  381. while (++index < length) {
  382. if (predicate(array[index], index, array)) {
  383. return true;
  384. }
  385. }
  386. return false;
  387. }
  388. function equalArrays(array, other, equalFunc, isLoose, stackA, stackB) {
  389. var index = -1,
  390. arrLength = array.length,
  391. othLength = other.length;
  392. if (arrLength !== othLength && !(isLoose && othLength > arrLength)) {
  393. return false;
  394. }
  395. // Ignore non-index properties.
  396. while (++index < arrLength) {
  397. var arrValue = array[index],
  398. othValue = other[index],
  399. result;
  400. if (result !== undefined) {
  401. if (result) {
  402. continue;
  403. }
  404. return false;
  405. }
  406. // Recursively compare arrays (susceptible to call stack limits).
  407. if (isLoose) {
  408. if (!arraySome(other, function(othValue) {
  409. return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB);
  410. })) {
  411. return false;
  412. }
  413. } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) {
  414. return false;
  415. }
  416. }
  417. return true;
  418. }
  419. function baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) {
  420. var objIsArr = isArray(object),
  421. othIsArr = isArray(other),
  422. objTag = arrayTag,
  423. othTag = arrayTag;
  424. if (!objIsArr) {
  425. objTag = objToString.call(object);
  426. if (objTag === argsTag) {
  427. objTag = objectTag;
  428. } else if (objTag !== objectTag) {
  429. objIsArr = isTypedArray(object);
  430. }
  431. }
  432. if (!othIsArr) {
  433. othTag = objToString.call(other);
  434. if (othTag === argsTag) {
  435. othTag = objectTag;
  436. }
  437. }
  438. var objIsObj = objTag === objectTag && !isHostObject(object),
  439. othIsObj = othTag === objectTag && !isHostObject(other),
  440. isSameTag = objTag === othTag;
  441. if (isSameTag && !(objIsArr || objIsObj)) {
  442. return equalByTag(object, other, objTag);
  443. }
  444. if (!isLoose) {
  445. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  446. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  447. if (objIsWrapped || othIsWrapped) {
  448. return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB);
  449. }
  450. }
  451. if (!isSameTag) {
  452. return false;
  453. }
  454. // Assume cyclic values are equal.
  455. // For more information on detecting circular references see https://es5.github.io/#JO.
  456. stackA || (stackA = []);
  457. stackB || (stackB = []);
  458. var length = stackA.length;
  459. while (length--) {
  460. if (stackA[length] === object) {
  461. return stackB[length] === other;
  462. }
  463. }
  464. // Add `object` and `other` to the stack of traversed objects.
  465. stackA.push(object);
  466. stackB.push(other);
  467. var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB);
  468. stackA.pop();
  469. stackB.pop();
  470. return result;
  471. }
  472. function baseIsEqual(value, other, isLoose, stackA, stackB) {
  473. if (value === other) {
  474. return true;
  475. }
  476. if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
  477. return value !== value && other !== other;
  478. }
  479. return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB);
  480. }
  481. var isEqual = Rx.internals.isEqual = function (value, other) {
  482. return baseIsEqual(value, other);
  483. };
  484. var hasProp = {}.hasOwnProperty,
  485. slice = Array.prototype.slice;
  486. var inherits = Rx.internals.inherits = function (child, parent) {
  487. function __() { this.constructor = child; }
  488. __.prototype = parent.prototype;
  489. child.prototype = new __();
  490. };
  491. var addProperties = Rx.internals.addProperties = function (obj) {
  492. for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
  493. for (var idx = 0, ln = sources.length; idx < ln; idx++) {
  494. var source = sources[idx];
  495. for (var prop in source) {
  496. obj[prop] = source[prop];
  497. }
  498. }
  499. };
  500. // Rx Utils
  501. var addRef = Rx.internals.addRef = function (xs, r) {
  502. return new AnonymousObservable(function (observer) {
  503. return new BinaryDisposable(r.getDisposable(), xs.subscribe(observer));
  504. });
  505. };
  506. function arrayInitialize(count, factory) {
  507. var a = new Array(count);
  508. for (var i = 0; i < count; i++) {
  509. a[i] = factory();
  510. }
  511. return a;
  512. }
  513. function IndexedItem(id, value) {
  514. this.id = id;
  515. this.value = value;
  516. }
  517. IndexedItem.prototype.compareTo = function (other) {
  518. var c = this.value.compareTo(other.value);
  519. c === 0 && (c = this.id - other.id);
  520. return c;
  521. };
  522. var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
  523. this.items = new Array(capacity);
  524. this.length = 0;
  525. };
  526. var priorityProto = PriorityQueue.prototype;
  527. priorityProto.isHigherPriority = function (left, right) {
  528. return this.items[left].compareTo(this.items[right]) < 0;
  529. };
  530. priorityProto.percolate = function (index) {
  531. if (index >= this.length || index < 0) { return; }
  532. var parent = index - 1 >> 1;
  533. if (parent < 0 || parent === index) { return; }
  534. if (this.isHigherPriority(index, parent)) {
  535. var temp = this.items[index];
  536. this.items[index] = this.items[parent];
  537. this.items[parent] = temp;
  538. this.percolate(parent);
  539. }
  540. };
  541. priorityProto.heapify = function (index) {
  542. +index || (index = 0);
  543. if (index >= this.length || index < 0) { return; }
  544. var left = 2 * index + 1,
  545. right = 2 * index + 2,
  546. first = index;
  547. if (left < this.length && this.isHigherPriority(left, first)) {
  548. first = left;
  549. }
  550. if (right < this.length && this.isHigherPriority(right, first)) {
  551. first = right;
  552. }
  553. if (first !== index) {
  554. var temp = this.items[index];
  555. this.items[index] = this.items[first];
  556. this.items[first] = temp;
  557. this.heapify(first);
  558. }
  559. };
  560. priorityProto.peek = function () { return this.items[0].value; };
  561. priorityProto.removeAt = function (index) {
  562. this.items[index] = this.items[--this.length];
  563. this.items[this.length] = undefined;
  564. this.heapify();
  565. };
  566. priorityProto.dequeue = function () {
  567. var result = this.peek();
  568. this.removeAt(0);
  569. return result;
  570. };
  571. priorityProto.enqueue = function (item) {
  572. var index = this.length++;
  573. this.items[index] = new IndexedItem(PriorityQueue.count++, item);
  574. this.percolate(index);
  575. };
  576. priorityProto.remove = function (item) {
  577. for (var i = 0; i < this.length; i++) {
  578. if (this.items[i].value === item) {
  579. this.removeAt(i);
  580. return true;
  581. }
  582. }
  583. return false;
  584. };
  585. PriorityQueue.count = 0;
  586. /**
  587. * Represents a group of disposable resources that are disposed together.
  588. * @constructor
  589. */
  590. var CompositeDisposable = Rx.CompositeDisposable = function () {
  591. var args = [], i, len;
  592. if (Array.isArray(arguments[0])) {
  593. args = arguments[0];
  594. } else {
  595. len = arguments.length;
  596. args = new Array(len);
  597. for(i = 0; i < len; i++) { args[i] = arguments[i]; }
  598. }
  599. this.disposables = args;
  600. this.isDisposed = false;
  601. this.length = args.length;
  602. };
  603. var CompositeDisposablePrototype = CompositeDisposable.prototype;
  604. /**
  605. * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
  606. * @param {Mixed} item Disposable to add.
  607. */
  608. CompositeDisposablePrototype.add = function (item) {
  609. if (this.isDisposed) {
  610. item.dispose();
  611. } else {
  612. this.disposables.push(item);
  613. this.length++;
  614. }
  615. };
  616. /**
  617. * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
  618. * @param {Mixed} item Disposable to remove.
  619. * @returns {Boolean} true if found; false otherwise.
  620. */
  621. CompositeDisposablePrototype.remove = function (item) {
  622. var shouldDispose = false;
  623. if (!this.isDisposed) {
  624. var idx = this.disposables.indexOf(item);
  625. if (idx !== -1) {
  626. shouldDispose = true;
  627. this.disposables.splice(idx, 1);
  628. this.length--;
  629. item.dispose();
  630. }
  631. }
  632. return shouldDispose;
  633. };
  634. /**
  635. * Disposes all disposables in the group and removes them from the group.
  636. */
  637. CompositeDisposablePrototype.dispose = function () {
  638. if (!this.isDisposed) {
  639. this.isDisposed = true;
  640. var len = this.disposables.length, currentDisposables = new Array(len);
  641. for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
  642. this.disposables = [];
  643. this.length = 0;
  644. for (i = 0; i < len; i++) {
  645. currentDisposables[i].dispose();
  646. }
  647. }
  648. };
  649. /**
  650. * Provides a set of static methods for creating Disposables.
  651. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
  652. */
  653. var Disposable = Rx.Disposable = function (action) {
  654. this.isDisposed = false;
  655. this.action = action || noop;
  656. };
  657. /** Performs the task of cleaning up resources. */
  658. Disposable.prototype.dispose = function () {
  659. if (!this.isDisposed) {
  660. this.action();
  661. this.isDisposed = true;
  662. }
  663. };
  664. /**
  665. * Creates a disposable object that invokes the specified action when disposed.
  666. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
  667. * @return {Disposable} The disposable object that runs the given action upon disposal.
  668. */
  669. var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
  670. /**
  671. * Gets the disposable that does nothing when disposed.
  672. */
  673. var disposableEmpty = Disposable.empty = { dispose: noop };
  674. /**
  675. * Validates whether the given object is a disposable
  676. * @param {Object} Object to test whether it has a dispose method
  677. * @returns {Boolean} true if a disposable object, else false.
  678. */
  679. var isDisposable = Disposable.isDisposable = function (d) {
  680. return d && isFunction(d.dispose);
  681. };
  682. var checkDisposed = Disposable.checkDisposed = function (disposable) {
  683. if (disposable.isDisposed) { throw new ObjectDisposedError(); }
  684. };
  685. var disposableFixup = Disposable._fixup = function (result) {
  686. return isDisposable(result) ? result : disposableEmpty;
  687. };
  688. // Single assignment
  689. var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
  690. this.isDisposed = false;
  691. this.current = null;
  692. };
  693. SingleAssignmentDisposable.prototype.getDisposable = function () {
  694. return this.current;
  695. };
  696. SingleAssignmentDisposable.prototype.setDisposable = function (value) {
  697. if (this.current) { throw new Error('Disposable has already been assigned'); }
  698. var shouldDispose = this.isDisposed;
  699. !shouldDispose && (this.current = value);
  700. shouldDispose && value && value.dispose();
  701. };
  702. SingleAssignmentDisposable.prototype.dispose = function () {
  703. if (!this.isDisposed) {
  704. this.isDisposed = true;
  705. var old = this.current;
  706. this.current = null;
  707. old && old.dispose();
  708. }
  709. };
  710. // Multiple assignment disposable
  711. var SerialDisposable = Rx.SerialDisposable = function () {
  712. this.isDisposed = false;
  713. this.current = null;
  714. };
  715. SerialDisposable.prototype.getDisposable = function () {
  716. return this.current;
  717. };
  718. SerialDisposable.prototype.setDisposable = function (value) {
  719. var shouldDispose = this.isDisposed;
  720. if (!shouldDispose) {
  721. var old = this.current;
  722. this.current = value;
  723. }
  724. old && old.dispose();
  725. shouldDispose && value && value.dispose();
  726. };
  727. SerialDisposable.prototype.dispose = function () {
  728. if (!this.isDisposed) {
  729. this.isDisposed = true;
  730. var old = this.current;
  731. this.current = null;
  732. }
  733. old && old.dispose();
  734. };
  735. var BinaryDisposable = Rx.BinaryDisposable = function (first, second) {
  736. this._first = first;
  737. this._second = second;
  738. this.isDisposed = false;
  739. };
  740. BinaryDisposable.prototype.dispose = function () {
  741. if (!this.isDisposed) {
  742. this.isDisposed = true;
  743. var old1 = this._first;
  744. this._first = null;
  745. old1 && old1.dispose();
  746. var old2 = this._second;
  747. this._second = null;
  748. old2 && old2.dispose();
  749. }
  750. };
  751. var NAryDisposable = Rx.NAryDisposable = function (disposables) {
  752. this._disposables = disposables;
  753. this.isDisposed = false;
  754. };
  755. NAryDisposable.prototype.dispose = function () {
  756. if (!this.isDisposed) {
  757. this.isDisposed = true;
  758. for (var i = 0, len = this._disposables.length; i < len; i++) {
  759. this._disposables[i].dispose();
  760. }
  761. this._disposables.length = 0;
  762. }
  763. };
  764. /**
  765. * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
  766. */
  767. var RefCountDisposable = Rx.RefCountDisposable = (function () {
  768. function InnerDisposable(disposable) {
  769. this.disposable = disposable;
  770. this.disposable.count++;
  771. this.isInnerDisposed = false;
  772. }
  773. InnerDisposable.prototype.dispose = function () {
  774. if (!this.disposable.isDisposed && !this.isInnerDisposed) {
  775. this.isInnerDisposed = true;
  776. this.disposable.count--;
  777. if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
  778. this.disposable.isDisposed = true;
  779. this.disposable.underlyingDisposable.dispose();
  780. }
  781. }
  782. };
  783. /**
  784. * Initializes a new instance of the RefCountDisposable with the specified disposable.
  785. * @constructor
  786. * @param {Disposable} disposable Underlying disposable.
  787. */
  788. function RefCountDisposable(disposable) {
  789. this.underlyingDisposable = disposable;
  790. this.isDisposed = false;
  791. this.isPrimaryDisposed = false;
  792. this.count = 0;
  793. }
  794. /**
  795. * Disposes the underlying disposable only when all dependent disposables have been disposed
  796. */
  797. RefCountDisposable.prototype.dispose = function () {
  798. if (!this.isDisposed && !this.isPrimaryDisposed) {
  799. this.isPrimaryDisposed = true;
  800. if (this.count === 0) {
  801. this.isDisposed = true;
  802. this.underlyingDisposable.dispose();
  803. }
  804. }
  805. };
  806. /**
  807. * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
  808. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
  809. */
  810. RefCountDisposable.prototype.getDisposable = function () {
  811. return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
  812. };
  813. return RefCountDisposable;
  814. })();
  815. function ScheduledDisposable(scheduler, disposable) {
  816. this.scheduler = scheduler;
  817. this.disposable = disposable;
  818. this.isDisposed = false;
  819. }
  820. function scheduleItem(s, self) {
  821. if (!self.isDisposed) {
  822. self.isDisposed = true;
  823. self.disposable.dispose();
  824. }
  825. }
  826. ScheduledDisposable.prototype.dispose = function () {
  827. this.scheduler.schedule(this, scheduleItem);
  828. };
  829. var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
  830. this.scheduler = scheduler;
  831. this.state = state;
  832. this.action = action;
  833. this.dueTime = dueTime;
  834. this.comparer = comparer || defaultSubComparer;
  835. this.disposable = new SingleAssignmentDisposable();
  836. };
  837. ScheduledItem.prototype.invoke = function () {
  838. this.disposable.setDisposable(this.invokeCore());
  839. };
  840. ScheduledItem.prototype.compareTo = function (other) {
  841. return this.comparer(this.dueTime, other.dueTime);
  842. };
  843. ScheduledItem.prototype.isCancelled = function () {
  844. return this.disposable.isDisposed;
  845. };
  846. ScheduledItem.prototype.invokeCore = function () {
  847. return disposableFixup(this.action(this.scheduler, this.state));
  848. };
  849. /** Provides a set of static properties to access commonly used schedulers. */
  850. var Scheduler = Rx.Scheduler = (function () {
  851. function Scheduler() { }
  852. /** Determines whether the given object is a scheduler */
  853. Scheduler.isScheduler = function (s) {
  854. return s instanceof Scheduler;
  855. };
  856. var schedulerProto = Scheduler.prototype;
  857. /**
  858. * Schedules an action to be executed.
  859. * @param state State passed to the action to be executed.
  860. * @param {Function} action Action to be executed.
  861. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  862. */
  863. schedulerProto.schedule = function (state, action) {
  864. throw new NotImplementedError();
  865. };
  866. /**
  867. * Schedules an action to be executed after dueTime.
  868. * @param state State passed to the action to be executed.
  869. * @param {Function} action Action to be executed.
  870. * @param {Number} dueTime Relative time after which to execute the action.
  871. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  872. */
  873. schedulerProto.scheduleFuture = function (state, dueTime, action) {
  874. var dt = dueTime;
  875. dt instanceof Date && (dt = dt - this.now());
  876. dt = Scheduler.normalize(dt);
  877. if (dt === 0) { return this.schedule(state, action); }
  878. return this._scheduleFuture(state, dt, action);
  879. };
  880. schedulerProto._scheduleFuture = function (state, dueTime, action) {
  881. throw new NotImplementedError();
  882. };
  883. /** Gets the current time according to the local machine's system clock. */
  884. Scheduler.now = defaultNow;
  885. /** Gets the current time according to the local machine's system clock. */
  886. Scheduler.prototype.now = defaultNow;
  887. /**
  888. * Normalizes the specified TimeSpan value to a positive value.
  889. * @param {Number} timeSpan The time span value to normalize.
  890. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
  891. */
  892. Scheduler.normalize = function (timeSpan) {
  893. timeSpan < 0 && (timeSpan = 0);
  894. return timeSpan;
  895. };
  896. return Scheduler;
  897. }());
  898. var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
  899. (function (schedulerProto) {
  900. function invokeRecImmediate(scheduler, pair) {
  901. var state = pair[0], action = pair[1], group = new CompositeDisposable();
  902. action(state, innerAction);
  903. return group;
  904. function innerAction(state2) {
  905. var isAdded = false, isDone = false;
  906. var d = scheduler.schedule(state2, scheduleWork);
  907. if (!isDone) {
  908. group.add(d);
  909. isAdded = true;
  910. }
  911. function scheduleWork(_, state3) {
  912. if (isAdded) {
  913. group.remove(d);
  914. } else {
  915. isDone = true;
  916. }
  917. action(state3, innerAction);
  918. return disposableEmpty;
  919. }
  920. }
  921. }
  922. function invokeRecDate(scheduler, pair) {
  923. var state = pair[0], action = pair[1], group = new CompositeDisposable();
  924. action(state, innerAction);
  925. return group;
  926. function innerAction(state2, dueTime1) {
  927. var isAdded = false, isDone = false;
  928. var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork);
  929. if (!isDone) {
  930. group.add(d);
  931. isAdded = true;
  932. }
  933. function scheduleWork(_, state3) {
  934. if (isAdded) {
  935. group.remove(d);
  936. } else {
  937. isDone = true;
  938. }
  939. action(state3, innerAction);
  940. return disposableEmpty;
  941. }
  942. }
  943. }
  944. /**
  945. * Schedules an action to be executed recursively.
  946. * @param {Mixed} state State passed to the action to be executed.
  947. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
  948. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  949. */
  950. schedulerProto.scheduleRecursive = function (state, action) {
  951. return this.schedule([state, action], invokeRecImmediate);
  952. };
  953. /**
  954. * Schedules an action to be executed recursively after a specified relative or absolute due time.
  955. * @param {Mixed} state State passed to the action to be executed.
  956. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
  957. * @param {Number | Date} dueTime Relative or absolute time after which to execute the action for the first time.
  958. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  959. */
  960. schedulerProto.scheduleRecursiveFuture = function (state, dueTime, action) {
  961. return this.scheduleFuture([state, action], dueTime, invokeRecDate);
  962. };
  963. }(Scheduler.prototype));
  964. (function (schedulerProto) {
  965. /**
  966. * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
  967. * @param {Mixed} state Initial state passed to the action upon the first iteration.
  968. * @param {Number} period Period for running the work periodically.
  969. * @param {Function} action Action to be executed, potentially updating the state.
  970. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
  971. */
  972. schedulerProto.schedulePeriodic = function(state, period, action) {
  973. if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
  974. period = normalizeTime(period);
  975. var s = state, id = root.setInterval(function () { s = action(s); }, period);
  976. return disposableCreate(function () { root.clearInterval(id); });
  977. };
  978. }(Scheduler.prototype));
  979. (function (schedulerProto) {
  980. /**
  981. * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
  982. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
  983. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
  984. */
  985. schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
  986. return new CatchScheduler(this, handler);
  987. };
  988. }(Scheduler.prototype));
  989. var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
  990. function createTick(self) {
  991. return function tick(command, recurse) {
  992. recurse(0, self._period);
  993. var state = tryCatch(self._action)(self._state);
  994. if (state === errorObj) {
  995. self._cancel.dispose();
  996. thrower(state.e);
  997. }
  998. self._state = state;
  999. };
  1000. }
  1001. function SchedulePeriodicRecursive(scheduler, state, period, action) {
  1002. this._scheduler = scheduler;
  1003. this._state = state;
  1004. this._period = period;
  1005. this._action = action;
  1006. }
  1007. SchedulePeriodicRecursive.prototype.start = function () {
  1008. var d = new SingleAssignmentDisposable();
  1009. this._cancel = d;
  1010. d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this)));
  1011. return d;
  1012. };
  1013. return SchedulePeriodicRecursive;
  1014. }());
  1015. /** Gets a scheduler that schedules work immediately on the current thread. */
  1016. var ImmediateScheduler = (function (__super__) {
  1017. inherits(ImmediateScheduler, __super__);
  1018. function ImmediateScheduler() {
  1019. __super__.call(this);
  1020. }
  1021. ImmediateScheduler.prototype.schedule = function (state, action) {
  1022. return disposableFixup(action(this, state));
  1023. };
  1024. return ImmediateScheduler;
  1025. }(Scheduler));
  1026. var immediateScheduler = Scheduler.immediate = new ImmediateScheduler();
  1027. /**
  1028. * Gets a scheduler that schedules work as soon as possible on the current thread.
  1029. */
  1030. var CurrentThreadScheduler = (function (__super__) {
  1031. var queue;
  1032. function runTrampoline () {
  1033. while (queue.length > 0) {
  1034. var item = queue.dequeue();
  1035. !item.isCancelled() && item.invoke();
  1036. }
  1037. }
  1038. inherits(CurrentThreadScheduler, __super__);
  1039. function CurrentThreadScheduler() {
  1040. __super__.call(this);
  1041. }
  1042. CurrentThreadScheduler.prototype.schedule = function (state, action) {
  1043. var si = new ScheduledItem(this, state, action, this.now());
  1044. if (!queue) {
  1045. queue = new PriorityQueue(4);
  1046. queue.enqueue(si);
  1047. var result = tryCatch(runTrampoline)();
  1048. queue = null;
  1049. if (result === errorObj) { thrower(result.e); }
  1050. } else {
  1051. queue.enqueue(si);
  1052. }
  1053. return si.disposable;
  1054. };
  1055. CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; };
  1056. return CurrentThreadScheduler;
  1057. }(Scheduler));
  1058. var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler();
  1059. var scheduleMethod, clearMethod;
  1060. var localTimer = (function () {
  1061. var localSetTimeout, localClearTimeout = noop;
  1062. if (!!root.setTimeout) {
  1063. localSetTimeout = root.setTimeout;
  1064. localClearTimeout = root.clearTimeout;
  1065. } else if (!!root.WScript) {
  1066. localSetTimeout = function (fn, time) {
  1067. root.WScript.Sleep(time);
  1068. fn();
  1069. };
  1070. } else {
  1071. throw new NotSupportedError();
  1072. }
  1073. return {
  1074. setTimeout: localSetTimeout,
  1075. clearTimeout: localClearTimeout
  1076. };
  1077. }());
  1078. var localSetTimeout = localTimer.setTimeout,
  1079. localClearTimeout = localTimer.clearTimeout;
  1080. (function () {
  1081. var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
  1082. clearMethod = function (handle) {
  1083. delete tasksByHandle[handle];
  1084. };
  1085. function runTask(handle) {
  1086. if (currentlyRunning) {
  1087. localSetTimeout(function () { runTask(handle); }, 0);
  1088. } else {
  1089. var task = tasksByHandle[handle];
  1090. if (task) {
  1091. currentlyRunning = true;
  1092. var result = tryCatch(task)();
  1093. clearMethod(handle);
  1094. currentlyRunning = false;
  1095. if (result === errorObj) { thrower(result.e); }
  1096. }
  1097. }
  1098. }
  1099. var reNative = new RegExp('^' +
  1100. String(toString)
  1101. .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  1102. .replace(/toString| for [^\]]+/g, '.*?') + '$'
  1103. );
  1104. var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
  1105. !reNative.test(setImmediate) && setImmediate;
  1106. function postMessageSupported () {
  1107. // Ensure not in a worker
  1108. if (!root.postMessage || root.importScripts) { return false; }
  1109. var isAsync = false, oldHandler = root.onmessage;
  1110. // Test for async
  1111. root.onmessage = function () { isAsync = true; };
  1112. root.postMessage('', '*');
  1113. root.onmessage = oldHandler;
  1114. return isAsync;
  1115. }
  1116. // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
  1117. if (isFunction(setImmediate)) {
  1118. scheduleMethod = function (action) {
  1119. var id = nextHandle++;
  1120. tasksByHandle[id] = action;
  1121. setImmediate(function () { runTask(id); });
  1122. return id;
  1123. };
  1124. } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
  1125. scheduleMethod = function (action) {
  1126. var id = nextHandle++;
  1127. tasksByHandle[id] = action;
  1128. process.nextTick(function () { runTask(id); });
  1129. return id;
  1130. };
  1131. } else if (postMessageSupported()) {
  1132. var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
  1133. var onGlobalPostMessage = function (event) {
  1134. // Only if we're a match to avoid any other global events
  1135. if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
  1136. runTask(event.data.substring(MSG_PREFIX.length));
  1137. }
  1138. };
  1139. root.addEventListener('message', onGlobalPostMessage, false);
  1140. scheduleMethod = function (action) {
  1141. var id = nextHandle++;
  1142. tasksByHandle[id] = action;
  1143. root.postMessage(MSG_PREFIX + id, '*');
  1144. return id;
  1145. };
  1146. } else if (!!root.MessageChannel) {
  1147. var channel = new root.MessageChannel();
  1148. channel.port1.onmessage = function (e) { runTask(e.data); };
  1149. scheduleMethod = function (action) {
  1150. var id = nextHandle++;
  1151. tasksByHandle[id] = action;
  1152. channel.port2.postMessage(id);
  1153. return id;
  1154. };
  1155. } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
  1156. scheduleMethod = function (action) {
  1157. var scriptElement = root.document.createElement('script');
  1158. var id = nextHandle++;
  1159. tasksByHandle[id] = action;
  1160. scriptElement.onreadystatechange = function () {
  1161. runTask(id);
  1162. scriptElement.onreadystatechange = null;
  1163. scriptElement.parentNode.removeChild(scriptElement);
  1164. scriptElement = null;
  1165. };
  1166. root.document.documentElement.appendChild(scriptElement);
  1167. return id;
  1168. };
  1169. } else {
  1170. scheduleMethod = function (action) {
  1171. var id = nextHandle++;
  1172. tasksByHandle[id] = action;
  1173. localSetTimeout(function () {
  1174. runTask(id);
  1175. }, 0);
  1176. return id;
  1177. };
  1178. }
  1179. }());
  1180. /**
  1181. * Gets a scheduler that schedules work via a timed callback based upon platform.
  1182. */
  1183. var DefaultScheduler = (function (__super__) {
  1184. inherits(DefaultScheduler, __super__);
  1185. function DefaultScheduler() {
  1186. __super__.call(this);
  1187. }
  1188. function scheduleAction(disposable, action, scheduler, state) {
  1189. return function schedule() {
  1190. disposable.setDisposable(Disposable._fixup(action(scheduler, state)));
  1191. };
  1192. }
  1193. function ClearDisposable(id) {
  1194. this._id = id;
  1195. this.isDisposed = false;
  1196. }
  1197. ClearDisposable.prototype.dispose = function () {
  1198. if (!this.isDisposed) {
  1199. this.isDisposed = true;
  1200. clearMethod(this._id);
  1201. }
  1202. };
  1203. function LocalClearDisposable(id) {
  1204. this._id = id;
  1205. this.isDisposed = false;
  1206. }
  1207. LocalClearDisposable.prototype.dispose = function () {
  1208. if (!this.isDisposed) {
  1209. this.isDisposed = true;
  1210. localClearTimeout(this._id);
  1211. }
  1212. };
  1213. DefaultScheduler.prototype.schedule = function (state, action) {
  1214. var disposable = new SingleAssignmentDisposable(),
  1215. id = scheduleMethod(scheduleAction(disposable, action, this, state));
  1216. return new BinaryDisposable(disposable, new ClearDisposable(id));
  1217. };
  1218. DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
  1219. if (dueTime === 0) { return this.schedule(state, action); }
  1220. var disposable = new SingleAssignmentDisposable(),
  1221. id = localSetTimeout(scheduleAction(disposable, action, this, state), dueTime);
  1222. return new BinaryDisposable(disposable, new LocalClearDisposable(id));
  1223. };
  1224. function scheduleLongRunning(state, action, disposable) {
  1225. return function () { action(state, disposable); };
  1226. }
  1227. DefaultScheduler.prototype.scheduleLongRunning = function (state, action) {
  1228. var disposable = disposableCreate(noop);
  1229. scheduleMethod(scheduleLongRunning(state, action, disposable));
  1230. return disposable;
  1231. };
  1232. return DefaultScheduler;
  1233. }(Scheduler));
  1234. var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler();
  1235. var CatchScheduler = (function (__super__) {
  1236. inherits(CatchScheduler, __super__);
  1237. function CatchScheduler(scheduler, handler) {
  1238. this._scheduler = scheduler;
  1239. this._handler = handler;
  1240. this._recursiveOriginal = null;
  1241. this._recursiveWrapper = null;
  1242. __super__.call(this);
  1243. }
  1244. CatchScheduler.prototype.schedule = function (state, action) {
  1245. return this._scheduler.schedule(state, this._wrap(action));
  1246. };
  1247. CatchScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
  1248. return this._scheduler.schedule(state, dueTime, this._wrap(action));
  1249. };
  1250. CatchScheduler.prototype.now = function () { return this._scheduler.now(); };
  1251. CatchScheduler.prototype._clone = function (scheduler) {
  1252. return new CatchScheduler(scheduler, this._handler);
  1253. };
  1254. CatchScheduler.prototype._wrap = function (action) {
  1255. var parent = this;
  1256. return function (self, state) {
  1257. var res = tryCatch(action)(parent._getRecursiveWrapper(self), state);
  1258. if (res === errorObj) {
  1259. if (!parent._handler(res.e)) { thrower(res.e); }
  1260. return disposableEmpty;
  1261. }
  1262. return disposableFixup(res);
  1263. };
  1264. };
  1265. CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
  1266. if (this._recursiveOriginal !== scheduler) {
  1267. this._recursiveOriginal = scheduler;
  1268. var wrapper = this._clone(scheduler);
  1269. wrapper._recursiveOriginal = scheduler;
  1270. wrapper._recursiveWrapper = wrapper;
  1271. this._recursiveWrapper = wrapper;
  1272. }
  1273. return this._recursiveWrapper;
  1274. };
  1275. CatchScheduler.prototype.schedulePeriodic = function (state, period, action) {
  1276. var self = this, failed = false, d = new SingleAssignmentDisposable();
  1277. d.setDisposable(this._scheduler.schedulePeriodic(state, period, function (state1) {
  1278. if (failed) { return null; }
  1279. var res = tryCatch(action)(state1);
  1280. if (res === errorObj) {
  1281. failed = true;
  1282. if (!self._handler(res.e)) { thrower(res.e); }
  1283. d.dispose();
  1284. return null;
  1285. }
  1286. return res;
  1287. }));
  1288. return d;
  1289. };
  1290. return CatchScheduler;
  1291. }(Scheduler));
  1292. /**
  1293. * Represents a notification to an observer.
  1294. */
  1295. var Notification = Rx.Notification = (function () {
  1296. function Notification() {
  1297. }
  1298. Notification.prototype._accept = function (onNext, onError, onCompleted) {
  1299. throw new NotImplementedError();
  1300. };
  1301. Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) {
  1302. throw new NotImplementedError();
  1303. };
  1304. /**
  1305. * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
  1306. * @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on..
  1307. * @param {Function} onError Function to invoke for an OnError notification.
  1308. * @param {Function} onCompleted Function to invoke for an OnCompleted notification.
  1309. * @returns {Any} Result produced by the observation.
  1310. */
  1311. Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
  1312. return observerOrOnNext && typeof observerOrOnNext === 'object' ?
  1313. this._acceptObserver(observerOrOnNext) :
  1314. this._accept(observerOrOnNext, onError, onCompleted);
  1315. };
  1316. /**
  1317. * Returns an observable sequence with a single notification.
  1318. *
  1319. * @memberOf Notifications
  1320. * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
  1321. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
  1322. */
  1323. Notification.prototype.toObservable = function (scheduler) {
  1324. var self = this;
  1325. isScheduler(scheduler) || (scheduler = immediateScheduler);
  1326. return new AnonymousObservable(function (o) {
  1327. return scheduler.schedule(self, function (_, notification) {
  1328. notification._acceptObserver(o);
  1329. notification.kind === 'N' && o.onCompleted();
  1330. });
  1331. });
  1332. };
  1333. return Notification;
  1334. })();
  1335. var OnNextNotification = (function (__super__) {
  1336. inherits(OnNextNotification, __super__);
  1337. function OnNextNotification(value) {
  1338. this.value = value;
  1339. this.kind = 'N';
  1340. }
  1341. OnNextNotification.prototype._accept = function (onNext) {
  1342. return onNext(this.value);
  1343. };
  1344. OnNextNotification.prototype._acceptObserver = function (o) {
  1345. return o.onNext(this.value);
  1346. };
  1347. OnNextNotification.prototype.toString = function () {
  1348. return 'OnNext(' + this.value + ')';
  1349. };
  1350. return OnNextNotification;
  1351. }(Notification));
  1352. var OnErrorNotification = (function (__super__) {
  1353. inherits(OnErrorNotification, __super__);
  1354. function OnErrorNotification(error) {
  1355. this.error = error;
  1356. this.kind = 'E';
  1357. }
  1358. OnErrorNotification.prototype._accept = function (onNext, onError) {
  1359. return onError(this.error);
  1360. };
  1361. OnErrorNotification.prototype._acceptObserver = function (o) {
  1362. return o.onError(this.error);
  1363. };
  1364. OnErrorNotification.prototype.toString = function () {
  1365. return 'OnError(' + this.error + ')';
  1366. };
  1367. return OnErrorNotification;
  1368. }(Notification));
  1369. var OnCompletedNotification = (function (__super__) {
  1370. inherits(OnCompletedNotification, __super__);
  1371. function OnCompletedNotification() {
  1372. this.kind = 'C';
  1373. }
  1374. OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) {
  1375. return onCompleted();
  1376. };
  1377. OnCompletedNotification.prototype._acceptObserver = function (o) {
  1378. return o.onCompleted();
  1379. };
  1380. OnCompletedNotification.prototype.toString = function () {
  1381. return 'OnCompleted()';
  1382. };
  1383. return OnCompletedNotification;
  1384. }(Notification));
  1385. /**
  1386. * Creates an object that represents an OnNext notification to an observer.
  1387. * @param {Any} value The value contained in the notification.
  1388. * @returns {Notification} The OnNext notification containing the value.
  1389. */
  1390. var notificationCreateOnNext = Notification.createOnNext = function (value) {
  1391. return new OnNextNotification(value);
  1392. };
  1393. /**
  1394. * Creates an object that represents an OnError notification to an observer.
  1395. * @param {Any} error The exception contained in the notification.
  1396. * @returns {Notification} The OnError notification containing the exception.
  1397. */
  1398. var notificationCreateOnError = Notification.createOnError = function (error) {
  1399. return new OnErrorNotification(error);
  1400. };
  1401. /**
  1402. * Creates an object that represents an OnCompleted notification to an observer.
  1403. * @returns {Notification} The OnCompleted notification.
  1404. */
  1405. var notificationCreateOnCompleted = Notification.createOnCompleted = function () {
  1406. return new OnCompletedNotification();
  1407. };
  1408. /**
  1409. * Supports push-style iteration over an observable sequence.
  1410. */
  1411. var Observer = Rx.Observer = function () { };
  1412. /**
  1413. * Creates a notification callback from an observer.
  1414. * @returns The action that forwards its input notification to the underlying observer.
  1415. */
  1416. Observer.prototype.toNotifier = function () {
  1417. var observer = this;
  1418. return function (n) { return n.accept(observer); };
  1419. };
  1420. /**
  1421. * Hides the identity of an observer.
  1422. * @returns An observer that hides the identity of the specified observer.
  1423. */
  1424. Observer.prototype.asObserver = function () {
  1425. var self = this;
  1426. return new AnonymousObserver(
  1427. function (x) { self.onNext(x); },
  1428. function (err) { self.onError(err); },
  1429. function () { self.onCompleted(); });
  1430. };
  1431. /**
  1432. * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
  1433. * If a violation is detected, an Error is thrown from the offending observer method call.
  1434. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
  1435. */
  1436. Observer.prototype.checked = function () { return new CheckedObserver(this); };
  1437. /**
  1438. * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
  1439. * @param {Function} [onNext] Observer's OnNext action implementation.
  1440. * @param {Function} [onError] Observer's OnError action implementation.
  1441. * @param {Function} [onCompleted] Observer's OnCompleted action implementation.
  1442. * @returns {Observer} The observer object implemented using the given actions.
  1443. */
  1444. var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
  1445. onNext || (onNext = noop);
  1446. onError || (onError = defaultError);
  1447. onCompleted || (onCompleted = noop);
  1448. return new AnonymousObserver(onNext, onError, onCompleted);
  1449. };
  1450. /**
  1451. * Creates an observer from a notification callback.
  1452. * @param {Function} handler Action that handles a notification.
  1453. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
  1454. */
  1455. Observer.fromNotifier = function (handler, thisArg) {
  1456. var cb = bindCallback(handler, thisArg, 1);
  1457. return new AnonymousObserver(function (x) {
  1458. return cb(notificationCreateOnNext(x));
  1459. }, function (e) {
  1460. return cb(notificationCreateOnError(e));
  1461. }, function () {
  1462. return cb(notificationCreateOnCompleted());
  1463. });
  1464. };
  1465. /**
  1466. * Schedules the invocation of observer methods on the given scheduler.
  1467. * @param {Scheduler} scheduler Scheduler to schedule observer messages on.
  1468. * @returns {Observer} Observer whose messages are scheduled on the given scheduler.
  1469. */
  1470. Observer.prototype.notifyOn = function (scheduler) {
  1471. return new ObserveOnObserver(scheduler, this);
  1472. };
  1473. Observer.prototype.makeSafe = function(disposable) {
  1474. return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
  1475. };
  1476. /**
  1477. * Abstract base class for implementations of the Observer class.
  1478. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
  1479. */
  1480. var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
  1481. inherits(AbstractObserver, __super__);
  1482. /**
  1483. * Creates a new observer in a non-stopped state.
  1484. */
  1485. function AbstractObserver() {
  1486. this.isStopped = false;
  1487. }
  1488. // Must be implemented by other observers
  1489. AbstractObserver.prototype.next = notImplemented;
  1490. AbstractObserver.prototype.error = notImplemented;
  1491. AbstractObserver.prototype.completed = notImplemented;
  1492. /**
  1493. * Notifies the observer of a new element in the sequence.
  1494. * @param {Any} value Next element in the sequence.
  1495. */
  1496. AbstractObserver.prototype.onNext = function (value) {
  1497. !this.isStopped && this.next(value);
  1498. };
  1499. /**
  1500. * Notifies the observer that an exception has occurred.
  1501. * @param {Any} error The error that has occurred.
  1502. */
  1503. AbstractObserver.prototype.onError = function (error) {
  1504. if (!this.isStopped) {
  1505. this.isStopped = true;
  1506. this.error(error);
  1507. }
  1508. };
  1509. /**
  1510. * Notifies the observer of the end of the sequence.
  1511. */
  1512. AbstractObserver.prototype.onCompleted = function () {
  1513. if (!this.isStopped) {
  1514. this.isStopped = true;
  1515. this.completed();
  1516. }
  1517. };
  1518. /**
  1519. * Disposes the observer, causing it to transition to the stopped state.
  1520. */
  1521. AbstractObserver.prototype.dispose = function () { this.isStopped = true; };
  1522. AbstractObserver.prototype.fail = function (e) {
  1523. if (!this.isStopped) {
  1524. this.isStopped = true;
  1525. this.error(e);
  1526. return true;
  1527. }
  1528. return false;
  1529. };
  1530. return AbstractObserver;
  1531. }(Observer));
  1532. /**
  1533. * Class to create an Observer instance from delegate-based implementations of the on* methods.
  1534. */
  1535. var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
  1536. inherits(AnonymousObserver, __super__);
  1537. /**
  1538. * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
  1539. * @param {Any} onNext Observer's OnNext action implementation.
  1540. * @param {Any} onError Observer's OnError action implementation.
  1541. * @param {Any} onCompleted Observer's OnCompleted action implementation.
  1542. */
  1543. function AnonymousObserver(onNext, onError, onCompleted) {
  1544. __super__.call(this);
  1545. this._onNext = onNext;
  1546. this._onError = onError;
  1547. this._onCompleted = onCompleted;
  1548. }
  1549. /**
  1550. * Calls the onNext action.
  1551. * @param {Any} value Next element in the sequence.
  1552. */
  1553. AnonymousObserver.prototype.next = function (value) {
  1554. this._onNext(value);
  1555. };
  1556. /**
  1557. * Calls the onError action.
  1558. * @param {Any} error The error that has occurred.
  1559. */
  1560. AnonymousObserver.prototype.error = function (error) {
  1561. this._onError(error);
  1562. };
  1563. /**
  1564. * Calls the onCompleted action.
  1565. */
  1566. AnonymousObserver.prototype.completed = function () {
  1567. this._onCompleted();
  1568. };
  1569. return AnonymousObserver;
  1570. }(AbstractObserver));
  1571. var CheckedObserver = (function (__super__) {
  1572. inherits(CheckedObserver, __super__);
  1573. function CheckedObserver(observer) {
  1574. __super__.call(this);
  1575. this._observer = observer;
  1576. this._state = 0; // 0 - idle, 1 - busy, 2 - done
  1577. }
  1578. var CheckedObserverPrototype = CheckedObserver.prototype;
  1579. CheckedObserverPrototype.onNext = function (value) {
  1580. this.checkAccess();
  1581. var res = tryCatch(this._observer.onNext).call(this._observer, value);
  1582. this._state = 0;
  1583. res === errorObj && thrower(res.e);
  1584. };
  1585. CheckedObserverPrototype.onError = function (err) {
  1586. this.checkAccess();
  1587. var res = tryCatch(this._observer.onError).call(this._observer, err);
  1588. this._state = 2;
  1589. res === errorObj && thrower(res.e);
  1590. };
  1591. CheckedObserverPrototype.onCompleted = function () {
  1592. this.checkAccess();
  1593. var res = tryCatch(this._observer.onCompleted).call(this._observer);
  1594. this._state = 2;
  1595. res === errorObj && thrower(res.e);
  1596. };
  1597. CheckedObserverPrototype.checkAccess = function () {
  1598. if (this._state === 1) { throw new Error('Re-entrancy detected'); }
  1599. if (this._state === 2) { throw new Error('Observer completed'); }
  1600. if (this._state === 0) { this._state = 1; }
  1601. };
  1602. return CheckedObserver;
  1603. }(Observer));
  1604. var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
  1605. inherits(ScheduledObserver, __super__);
  1606. function ScheduledObserver(scheduler, observer) {
  1607. __super__.call(this);
  1608. this.scheduler = scheduler;
  1609. this.observer = observer;
  1610. this.isAcquired = false;
  1611. this.hasFaulted = false;
  1612. this.queue = [];
  1613. this.disposable = new SerialDisposable();
  1614. }
  1615. function enqueueNext(observer, x) { return function () { observer.onNext(x); }; }
  1616. function enqueueError(observer, e) { return function () { observer.onError(e); }; }
  1617. function enqueueCompleted(observer) { return function () { observer.onCompleted(); }; }
  1618. ScheduledObserver.prototype.next = function (x) {
  1619. this.queue.push(enqueueNext(this.observer, x));
  1620. };
  1621. ScheduledObserver.prototype.error = function (e) {
  1622. this.queue.push(enqueueError(this.observer, e));
  1623. };
  1624. ScheduledObserver.prototype.completed = function () {
  1625. this.queue.push(enqueueCompleted(this.observer));
  1626. };
  1627. function scheduleMethod(state, recurse) {
  1628. var work;
  1629. if (state.queue.length > 0) {
  1630. work = state.queue.shift();
  1631. } else {
  1632. state.isAcquired = false;
  1633. return;
  1634. }
  1635. var res = tryCatch(work)();
  1636. if (res === errorObj) {
  1637. state.queue = [];
  1638. state.hasFaulted = true;
  1639. return thrower(res.e);
  1640. }
  1641. recurse(state);
  1642. }
  1643. ScheduledObserver.prototype.ensureActive = function () {
  1644. var isOwner = false;
  1645. if (!this.hasFaulted && this.queue.length > 0) {
  1646. isOwner = !this.isAcquired;
  1647. this.isAcquired = true;
  1648. }
  1649. isOwner &&
  1650. this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, scheduleMethod));
  1651. };
  1652. ScheduledObserver.prototype.dispose = function () {
  1653. __super__.prototype.dispose.call(this);
  1654. this.disposable.dispose();
  1655. };
  1656. return ScheduledObserver;
  1657. }(AbstractObserver));
  1658. var ObserveOnObserver = (function (__super__) {
  1659. inherits(ObserveOnObserver, __super__);
  1660. function ObserveOnObserver(scheduler, observer, cancel) {
  1661. __super__.call(this, scheduler, observer);
  1662. this._cancel = cancel;
  1663. }
  1664. ObserveOnObserver.prototype.next = function (value) {
  1665. __super__.prototype.next.call(this, value);
  1666. this.ensureActive();
  1667. };
  1668. ObserveOnObserver.prototype.error = function (e) {
  1669. __super__.prototype.error.call(this, e);
  1670. this.ensureActive();
  1671. };
  1672. ObserveOnObserver.prototype.completed = function () {
  1673. __super__.prototype.completed.call(this);
  1674. this.ensureActive();
  1675. };
  1676. ObserveOnObserver.prototype.dispose = function () {
  1677. __super__.prototype.dispose.call(this);
  1678. this._cancel && this._cancel.dispose();
  1679. this._cancel = null;
  1680. };
  1681. return ObserveOnObserver;
  1682. })(ScheduledObserver);
  1683. var observableProto;
  1684. /**
  1685. * Represents a push-style collection.
  1686. */
  1687. var Observable = Rx.Observable = (function () {
  1688. function makeSubscribe(self, subscribe) {
  1689. return function (o) {
  1690. var oldOnError = o.onError;
  1691. o.onError = function (e) {
  1692. makeStackTraceLong(e, self);
  1693. oldOnError.call(o, e);
  1694. };
  1695. return subscribe.call(self, o);
  1696. };
  1697. }
  1698. function Observable() {
  1699. if (Rx.config.longStackSupport && hasStacks) {
  1700. var oldSubscribe = this._subscribe;
  1701. var e = tryCatch(thrower)(new Error()).e;
  1702. this.stack = e.stack.substring(e.stack.indexOf('\n') + 1);
  1703. this._subscribe = makeSubscribe(this, oldSubscribe);
  1704. }
  1705. }
  1706. observableProto = Observable.prototype;
  1707. /**
  1708. * Determines whether the given object is an Observable
  1709. * @param {Any} An object to determine whether it is an Observable
  1710. * @returns {Boolean} true if an Observable, else false.
  1711. */
  1712. Observable.isObservable = function (o) {
  1713. return o && isFunction(o.subscribe);
  1714. };
  1715. /**
  1716. * Subscribes an o to the observable sequence.
  1717. * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
  1718. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
  1719. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
  1720. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
  1721. */
  1722. observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
  1723. return this._subscribe(typeof oOrOnNext === 'object' ?
  1724. oOrOnNext :
  1725. observerCreate(oOrOnNext, onError, onCompleted));
  1726. };
  1727. /**
  1728. * Subscribes to the next value in the sequence with an optional "this" argument.
  1729. * @param {Function} onNext The function to invoke on each element in the observable sequence.
  1730. * @param {Any} [thisArg] Object to use as this when executing callback.
  1731. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
  1732. */
  1733. observableProto.subscribeOnNext = function (onNext, thisArg) {
  1734. return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
  1735. };
  1736. /**
  1737. * Subscribes to an exceptional condition in the sequence with an optional "this" argument.
  1738. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
  1739. * @param {Any} [thisArg] Object to use as this when executing callback.
  1740. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
  1741. */
  1742. observableProto.subscribeOnError = function (onError, thisArg) {
  1743. return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
  1744. };
  1745. /**
  1746. * Subscribes to the next value in the sequence with an optional "this" argument.
  1747. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
  1748. * @param {Any} [thisArg] Object to use as this when executing callback.
  1749. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
  1750. */
  1751. observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
  1752. return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
  1753. };
  1754. return Observable;
  1755. })();
  1756. var ObservableBase = Rx.ObservableBase = (function (__super__) {
  1757. inherits(ObservableBase, __super__);
  1758. function fixSubscriber(subscriber) {
  1759. return subscriber && isFunction(subscriber.dispose) ? subscriber :
  1760. isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
  1761. }
  1762. function setDisposable(s, state) {
  1763. var ado = state[0], self = state[1];
  1764. var sub = tryCatch(self.subscribeCore).call(self, ado);
  1765. if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
  1766. ado.setDisposable(fixSubscriber(sub));
  1767. }
  1768. function ObservableBase() {
  1769. __super__.call(this);
  1770. }
  1771. ObservableBase.prototype._subscribe = function (o) {
  1772. var ado = new AutoDetachObserver(o), state = [ado, this];
  1773. if (currentThreadScheduler.scheduleRequired()) {
  1774. currentThreadScheduler.schedule(state, setDisposable);
  1775. } else {
  1776. setDisposable(null, state);
  1777. }
  1778. return ado;
  1779. };
  1780. ObservableBase.prototype.subscribeCore = notImplemented;
  1781. return ObservableBase;
  1782. }(Observable));
  1783. var FlatMapObservable = Rx.FlatMapObservable = (function(__super__) {
  1784. inherits(FlatMapObservable, __super__);
  1785. function FlatMapObservable(source, selector, resultSelector, thisArg) {
  1786. this.resultSelector = isFunction(resultSelector) ? resultSelector : null;
  1787. this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3);
  1788. this.source = source;
  1789. __super__.call(this);
  1790. }
  1791. FlatMapObservable.prototype.subscribeCore = function(o) {
  1792. return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this));
  1793. };
  1794. inherits(InnerObserver, AbstractObserver);
  1795. function InnerObserver(observer, selector, resultSelector, source) {
  1796. this.i = 0;
  1797. this.selector = selector;
  1798. this.resultSelector = resultSelector;
  1799. this.source = source;
  1800. this.o = observer;
  1801. AbstractObserver.call(this);
  1802. }
  1803. InnerObserver.prototype._wrapResult = function(result, x, i) {
  1804. return this.resultSelector ?
  1805. result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) :
  1806. result;
  1807. };
  1808. InnerObserver.prototype.next = function(x) {
  1809. var i = this.i++;
  1810. var result = tryCatch(this.selector)(x, i, this.source);
  1811. if (result === errorObj) { return this.o.onError(result.e); }
  1812. isPromise(result) && (result = observableFromPromise(result));
  1813. (isArrayLike(result) || isIterable(result)) && (result = Observable.from(result));
  1814. this.o.onNext(this._wrapResult(result, x, i));
  1815. };
  1816. InnerObserver.prototype.error = function(e) { this.o.onError(e); };
  1817. InnerObserver.prototype.completed = function() { this.o.onCompleted(); };
  1818. return FlatMapObservable;
  1819. }(ObservableBase));
  1820. var Enumerable = Rx.internals.Enumerable = function () { };
  1821. function IsDisposedDisposable(state) {
  1822. this._s = state;
  1823. this.isDisposed = false;
  1824. }
  1825. IsDisposedDisposable.prototype.dispose = function () {
  1826. if (!this.isDisposed) {
  1827. this.isDisposed = true;
  1828. this._s.isDisposed = true;
  1829. }
  1830. };
  1831. var ConcatEnumerableObservable = (function(__super__) {
  1832. inherits(ConcatEnumerableObservable, __super__);
  1833. function ConcatEnumerableObservable(sources) {
  1834. this.sources = sources;
  1835. __super__.call(this);
  1836. }
  1837. function scheduleMethod(state, recurse) {
  1838. if (state.isDisposed) { return; }
  1839. var currentItem = tryCatch(state.e.next).call(state.e);
  1840. if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
  1841. if (currentItem.done) { return state.o.onCompleted(); }
  1842. // Check if promise
  1843. var currentValue = currentItem.value;
  1844. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  1845. var d = new SingleAssignmentDisposable();
  1846. state.subscription.setDisposable(d);
  1847. d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
  1848. }
  1849. ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
  1850. var subscription = new SerialDisposable();
  1851. var state = {
  1852. isDisposed: false,
  1853. o: o,
  1854. subscription: subscription,
  1855. e: this.sources[$iterator$]()
  1856. };
  1857. var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
  1858. return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
  1859. };
  1860. function InnerObserver(state, recurse) {
  1861. this._state = state;
  1862. this._recurse = recurse;
  1863. AbstractObserver.call(this);
  1864. }
  1865. inherits(InnerObserver, AbstractObserver);
  1866. InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  1867. InnerObserver.prototype.error = function (e) { this._state.o.onError(e); };
  1868. InnerObserver.prototype.completed = function () { this._recurse(this._state); };
  1869. return ConcatEnumerableObservable;
  1870. }(ObservableBase));
  1871. Enumerable.prototype.concat = function () {
  1872. return new ConcatEnumerableObservable(this);
  1873. };
  1874. var CatchErrorObservable = (function(__super__) {
  1875. function CatchErrorObservable(sources) {
  1876. this.sources = sources;
  1877. __super__.call(this);
  1878. }
  1879. inherits(CatchErrorObservable, __super__);
  1880. function scheduleMethod(state, recurse) {
  1881. if (state.isDisposed) { return; }
  1882. var currentItem = tryCatch(state.e.next).call(state.e);
  1883. if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
  1884. if (currentItem.done) { return state.lastError !== null ? state.o.onError(state.lastError) : state.o.onCompleted(); }
  1885. var currentValue = currentItem.value;
  1886. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  1887. var d = new SingleAssignmentDisposable();
  1888. state.subscription.setDisposable(d);
  1889. d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
  1890. }
  1891. CatchErrorObservable.prototype.subscribeCore = function (o) {
  1892. var subscription = new SerialDisposable();
  1893. var state = {
  1894. isDisposed: false,
  1895. e: this.sources[$iterator$](),
  1896. subscription: subscription,
  1897. lastError: null,
  1898. o: o
  1899. };
  1900. var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
  1901. return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
  1902. };
  1903. function InnerObserver(state, recurse) {
  1904. this._state = state;
  1905. this._recurse = recurse;
  1906. AbstractObserver.call(this);
  1907. }
  1908. inherits(InnerObserver, AbstractObserver);
  1909. InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  1910. InnerObserver.prototype.error = function (e) { this._state.lastError = e; this._recurse(this._state); };
  1911. InnerObserver.prototype.completed = function () { this._state.o.onCompleted(); };
  1912. return CatchErrorObservable;
  1913. }(ObservableBase));
  1914. Enumerable.prototype.catchError = function () {
  1915. return new CatchErrorObservable(this);
  1916. };
  1917. var RepeatEnumerable = (function (__super__) {
  1918. inherits(RepeatEnumerable, __super__);
  1919. function RepeatEnumerable(v, c) {
  1920. this.v = v;
  1921. this.c = c == null ? -1 : c;
  1922. }
  1923. RepeatEnumerable.prototype[$iterator$] = function () {
  1924. return new RepeatEnumerator(this);
  1925. };
  1926. function RepeatEnumerator(p) {
  1927. this.v = p.v;
  1928. this.l = p.c;
  1929. }
  1930. RepeatEnumerator.prototype.next = function () {
  1931. if (this.l === 0) { return doneEnumerator; }
  1932. if (this.l > 0) { this.l--; }
  1933. return { done: false, value: this.v };
  1934. };
  1935. return RepeatEnumerable;
  1936. }(Enumerable));
  1937. var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
  1938. return new RepeatEnumerable(value, repeatCount);
  1939. };
  1940. var OfEnumerable = (function(__super__) {
  1941. inherits(OfEnumerable, __super__);
  1942. function OfEnumerable(s, fn, thisArg) {
  1943. this.s = s;
  1944. this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
  1945. }
  1946. OfEnumerable.prototype[$iterator$] = function () {
  1947. return new OfEnumerator(this);
  1948. };
  1949. function OfEnumerator(p) {
  1950. this.i = -1;
  1951. this.s = p.s;
  1952. this.l = this.s.length;
  1953. this.fn = p.fn;
  1954. }
  1955. OfEnumerator.prototype.next = function () {
  1956. return ++this.i < this.l ?
  1957. { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
  1958. doneEnumerator;
  1959. };
  1960. return OfEnumerable;
  1961. }(Enumerable));
  1962. var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
  1963. return new OfEnumerable(source, selector, thisArg);
  1964. };
  1965. var ObserveOnObservable = (function (__super__) {
  1966. inherits(ObserveOnObservable, __super__);
  1967. function ObserveOnObservable(source, s) {
  1968. this.source = source;
  1969. this._s = s;
  1970. __super__.call(this);
  1971. }
  1972. ObserveOnObservable.prototype.subscribeCore = function (o) {
  1973. return this.source.subscribe(new ObserveOnObserver(this._s, o));
  1974. };
  1975. return ObserveOnObservable;
  1976. }(ObservableBase));
  1977. /**
  1978. * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
  1979. *
  1980. * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
  1981. * that require to be run on a scheduler, use subscribeOn.
  1982. *
  1983. * @param {Scheduler} scheduler Scheduler to notify observers on.
  1984. * @returns {Observable} The source sequence whose observations happen on the specified scheduler.
  1985. */
  1986. observableProto.observeOn = function (scheduler) {
  1987. return new ObserveOnObservable(this, scheduler);
  1988. };
  1989. var SubscribeOnObservable = (function (__super__) {
  1990. inherits(SubscribeOnObservable, __super__);
  1991. function SubscribeOnObservable(source, s) {
  1992. this.source = source;
  1993. this._s = s;
  1994. __super__.call(this);
  1995. }
  1996. function scheduleMethod(scheduler, state) {
  1997. var source = state[0], d = state[1], o = state[2];
  1998. d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o)));
  1999. }
  2000. SubscribeOnObservable.prototype.subscribeCore = function (o) {
  2001. var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
  2002. d.setDisposable(m);
  2003. m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod));
  2004. return d;
  2005. };
  2006. return SubscribeOnObservable;
  2007. }(ObservableBase));
  2008. /**
  2009. * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
  2010. * see the remarks section for more information on the distinction between subscribeOn and observeOn.
  2011. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
  2012. * callbacks on a scheduler, use observeOn.
  2013. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
  2014. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
  2015. */
  2016. observableProto.subscribeOn = function (scheduler) {
  2017. return new SubscribeOnObservable(this, scheduler);
  2018. };
  2019. var FromPromiseObservable = (function(__super__) {
  2020. inherits(FromPromiseObservable, __super__);
  2021. function FromPromiseObservable(p, s) {
  2022. this._p = p;
  2023. this._s = s;
  2024. __super__.call(this);
  2025. }
  2026. function scheduleNext(s, state) {
  2027. var o = state[0], data = state[1];
  2028. o.onNext(data);
  2029. o.onCompleted();
  2030. }
  2031. function scheduleError(s, state) {
  2032. var o = state[0], err = state[1];
  2033. o.onError(err);
  2034. }
  2035. FromPromiseObservable.prototype.subscribeCore = function(o) {
  2036. var sad = new SingleAssignmentDisposable(), self = this, p = this._p;
  2037. if (isFunction(p)) {
  2038. p = tryCatch(p)();
  2039. if (p === errorObj) {
  2040. o.onError(p.e);
  2041. return sad;
  2042. }
  2043. }
  2044. p
  2045. .then(function (data) {
  2046. sad.setDisposable(self._s.schedule([o, data], scheduleNext));
  2047. }, function (err) {
  2048. sad.setDisposable(self._s.schedule([o, err], scheduleError));
  2049. });
  2050. return sad;
  2051. };
  2052. return FromPromiseObservable;
  2053. }(ObservableBase));
  2054. /**
  2055. * Converts a Promise to an Observable sequence
  2056. * @param {Promise} An ES6 Compliant promise.
  2057. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
  2058. */
  2059. var observableFromPromise = Observable.fromPromise = function (promise, scheduler) {
  2060. scheduler || (scheduler = defaultScheduler);
  2061. return new FromPromiseObservable(promise, scheduler);
  2062. };
  2063. /*
  2064. * Converts an existing observable sequence to an ES6 Compatible Promise
  2065. * @example
  2066. * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
  2067. *
  2068. * // With config
  2069. * Rx.config.Promise = RSVP.Promise;
  2070. * var promise = Rx.Observable.return(42).toPromise();
  2071. * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
  2072. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
  2073. */
  2074. observableProto.toPromise = function (promiseCtor) {
  2075. promiseCtor || (promiseCtor = Rx.config.Promise);
  2076. if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
  2077. var source = this;
  2078. return new promiseCtor(function (resolve, reject) {
  2079. // No cancellation can be done
  2080. var value;
  2081. source.subscribe(function (v) {
  2082. value = v;
  2083. }, reject, function () {
  2084. resolve(value);
  2085. });
  2086. });
  2087. };
  2088. var ToArrayObservable = (function(__super__) {
  2089. inherits(ToArrayObservable, __super__);
  2090. function ToArrayObservable(source) {
  2091. this.source = source;
  2092. __super__.call(this);
  2093. }
  2094. ToArrayObservable.prototype.subscribeCore = function(o) {
  2095. return this.source.subscribe(new InnerObserver(o));
  2096. };
  2097. inherits(InnerObserver, AbstractObserver);
  2098. function InnerObserver(o) {
  2099. this.o = o;
  2100. this.a = [];
  2101. AbstractObserver.call(this);
  2102. }
  2103. InnerObserver.prototype.next = function (x) { this.a.push(x); };
  2104. InnerObserver.prototype.error = function (e) { this.o.onError(e); };
  2105. InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); };
  2106. return ToArrayObservable;
  2107. }(ObservableBase));
  2108. /**
  2109. * Creates an array from an observable sequence.
  2110. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
  2111. */
  2112. observableProto.toArray = function () {
  2113. return new ToArrayObservable(this);
  2114. };
  2115. /**
  2116. * Creates an observable sequence from a specified subscribe method implementation.
  2117. * @example
  2118. * var res = Rx.Observable.create(function (observer) { return function () { } );
  2119. * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
  2120. * var res = Rx.Observable.create(function (observer) { } );
  2121. * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
  2122. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
  2123. */
  2124. Observable.create = function (subscribe, parent) {
  2125. return new AnonymousObservable(subscribe, parent);
  2126. };
  2127. var Defer = (function(__super__) {
  2128. inherits(Defer, __super__);
  2129. function Defer(factory) {
  2130. this._f = factory;
  2131. __super__.call(this);
  2132. }
  2133. Defer.prototype.subscribeCore = function (o) {
  2134. var result = tryCatch(this._f)();
  2135. if (result === errorObj) { return observableThrow(result.e).subscribe(o);}
  2136. isPromise(result) && (result = observableFromPromise(result));
  2137. return result.subscribe(o);
  2138. };
  2139. return Defer;
  2140. }(ObservableBase));
  2141. /**
  2142. * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
  2143. *
  2144. * @example
  2145. * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
  2146. * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
  2147. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
  2148. */
  2149. var observableDefer = Observable.defer = function (observableFactory) {
  2150. return new Defer(observableFactory);
  2151. };
  2152. var EmptyObservable = (function(__super__) {
  2153. inherits(EmptyObservable, __super__);
  2154. function EmptyObservable(scheduler) {
  2155. this.scheduler = scheduler;
  2156. __super__.call(this);
  2157. }
  2158. EmptyObservable.prototype.subscribeCore = function (observer) {
  2159. var sink = new EmptySink(observer, this.scheduler);
  2160. return sink.run();
  2161. };
  2162. function EmptySink(observer, scheduler) {
  2163. this.observer = observer;
  2164. this.scheduler = scheduler;
  2165. }
  2166. function scheduleItem(s, state) {
  2167. state.onCompleted();
  2168. return disposableEmpty;
  2169. }
  2170. EmptySink.prototype.run = function () {
  2171. var state = this.observer;
  2172. return this.scheduler === immediateScheduler ?
  2173. scheduleItem(null, state) :
  2174. this.scheduler.schedule(state, scheduleItem);
  2175. };
  2176. return EmptyObservable;
  2177. }(ObservableBase));
  2178. var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler);
  2179. /**
  2180. * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
  2181. *
  2182. * @example
  2183. * var res = Rx.Observable.empty();
  2184. * var res = Rx.Observable.empty(Rx.Scheduler.timeout);
  2185. * @param {Scheduler} [scheduler] Scheduler to send the termination call on.
  2186. * @returns {Observable} An observable sequence with no elements.
  2187. */
  2188. var observableEmpty = Observable.empty = function (scheduler) {
  2189. isScheduler(scheduler) || (scheduler = immediateScheduler);
  2190. return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler);
  2191. };
  2192. var FromObservable = (function(__super__) {
  2193. inherits(FromObservable, __super__);
  2194. function FromObservable(iterable, fn, scheduler) {
  2195. this._iterable = iterable;
  2196. this._fn = fn;
  2197. this._scheduler = scheduler;
  2198. __super__.call(this);
  2199. }
  2200. function createScheduleMethod(o, it, fn) {
  2201. return function loopRecursive(i, recurse) {
  2202. var next = tryCatch(it.next).call(it);
  2203. if (next === errorObj) { return o.onError(next.e); }
  2204. if (next.done) { return o.onCompleted(); }
  2205. var result = next.value;
  2206. if (isFunction(fn)) {
  2207. result = tryCatch(fn)(result, i);
  2208. if (result === errorObj) { return o.onError(result.e); }
  2209. }
  2210. o.onNext(result);
  2211. recurse(i + 1);
  2212. };
  2213. }
  2214. FromObservable.prototype.subscribeCore = function (o) {
  2215. var list = Object(this._iterable),
  2216. it = getIterable(list);
  2217. return this._scheduler.scheduleRecursive(0, createScheduleMethod(o, it, this._fn));
  2218. };
  2219. return FromObservable;
  2220. }(ObservableBase));
  2221. var maxSafeInteger = Math.pow(2, 53) - 1;
  2222. function StringIterable(s) {
  2223. this._s = s;
  2224. }
  2225. StringIterable.prototype[$iterator$] = function () {
  2226. return new StringIterator(this._s);
  2227. };
  2228. function StringIterator(s) {
  2229. this._s = s;
  2230. this._l = s.length;
  2231. this._i = 0;
  2232. }
  2233. StringIterator.prototype[$iterator$] = function () {
  2234. return this;
  2235. };
  2236. StringIterator.prototype.next = function () {
  2237. return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
  2238. };
  2239. function ArrayIterable(a) {
  2240. this._a = a;
  2241. }
  2242. ArrayIterable.prototype[$iterator$] = function () {
  2243. return new ArrayIterator(this._a);
  2244. };
  2245. function ArrayIterator(a) {
  2246. this._a = a;
  2247. this._l = toLength(a);
  2248. this._i = 0;
  2249. }
  2250. ArrayIterator.prototype[$iterator$] = function () {
  2251. return this;
  2252. };
  2253. ArrayIterator.prototype.next = function () {
  2254. return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
  2255. };
  2256. function numberIsFinite(value) {
  2257. return typeof value === 'number' && root.isFinite(value);
  2258. }
  2259. function isNan(n) {
  2260. return n !== n;
  2261. }
  2262. function getIterable(o) {
  2263. var i = o[$iterator$], it;
  2264. if (!i && typeof o === 'string') {
  2265. it = new StringIterable(o);
  2266. return it[$iterator$]();
  2267. }
  2268. if (!i && o.length !== undefined) {
  2269. it = new ArrayIterable(o);
  2270. return it[$iterator$]();
  2271. }
  2272. if (!i) { throw new TypeError('Object is not iterable'); }
  2273. return o[$iterator$]();
  2274. }
  2275. function sign(value) {
  2276. var number = +value;
  2277. if (number === 0) { return number; }
  2278. if (isNaN(number)) { return number; }
  2279. return number < 0 ? -1 : 1;
  2280. }
  2281. function toLength(o) {
  2282. var len = +o.length;
  2283. if (isNaN(len)) { return 0; }
  2284. if (len === 0 || !numberIsFinite(len)) { return len; }
  2285. len = sign(len) * Math.floor(Math.abs(len));
  2286. if (len <= 0) { return 0; }
  2287. if (len > maxSafeInteger) { return maxSafeInteger; }
  2288. return len;
  2289. }
  2290. /**
  2291. * This method creates a new Observable sequence from an array-like or iterable object.
  2292. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
  2293. * @param {Function} [mapFn] Map function to call on every element of the array.
  2294. * @param {Any} [thisArg] The context to use calling the mapFn if provided.
  2295. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
  2296. */
  2297. var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
  2298. if (iterable == null) {
  2299. throw new Error('iterable cannot be null.')
  2300. }
  2301. if (mapFn && !isFunction(mapFn)) {
  2302. throw new Error('mapFn when provided must be a function');
  2303. }
  2304. if (mapFn) {
  2305. var mapper = bindCallback(mapFn, thisArg, 2);
  2306. }
  2307. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2308. return new FromObservable(iterable, mapper, scheduler);
  2309. }
  2310. var FromArrayObservable = (function(__super__) {
  2311. inherits(FromArrayObservable, __super__);
  2312. function FromArrayObservable(args, scheduler) {
  2313. this._args = args;
  2314. this._scheduler = scheduler;
  2315. __super__.call(this);
  2316. }
  2317. function scheduleMethod(o, args) {
  2318. var len = args.length;
  2319. return function loopRecursive (i, recurse) {
  2320. if (i < len) {
  2321. o.onNext(args[i]);
  2322. recurse(i + 1);
  2323. } else {
  2324. o.onCompleted();
  2325. }
  2326. };
  2327. }
  2328. FromArrayObservable.prototype.subscribeCore = function (o) {
  2329. return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._args));
  2330. };
  2331. return FromArrayObservable;
  2332. }(ObservableBase));
  2333. /**
  2334. * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
  2335. * @deprecated use Observable.from or Observable.of
  2336. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
  2337. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
  2338. */
  2339. var observableFromArray = Observable.fromArray = function (array, scheduler) {
  2340. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2341. return new FromArrayObservable(array, scheduler)
  2342. };
  2343. var GenerateObservable = (function (__super__) {
  2344. inherits(GenerateObservable, __super__);
  2345. function GenerateObservable(state, cndFn, itrFn, resFn, s) {
  2346. this._initialState = state;
  2347. this._cndFn = cndFn;
  2348. this._itrFn = itrFn;
  2349. this._resFn = resFn;
  2350. this._s = s;
  2351. __super__.call(this);
  2352. }
  2353. function scheduleRecursive(state, recurse) {
  2354. if (state.first) {
  2355. state.first = false;
  2356. } else {
  2357. state.newState = tryCatch(state.self._itrFn)(state.newState);
  2358. if (state.newState === errorObj) { return state.o.onError(state.newState.e); }
  2359. }
  2360. var hasResult = tryCatch(state.self._cndFn)(state.newState);
  2361. if (hasResult === errorObj) { return state.o.onError(hasResult.e); }
  2362. if (hasResult) {
  2363. var result = tryCatch(state.self._resFn)(state.newState);
  2364. if (result === errorObj) { return state.o.onError(result.e); }
  2365. state.o.onNext(result);
  2366. recurse(state);
  2367. } else {
  2368. state.o.onCompleted();
  2369. }
  2370. }
  2371. GenerateObservable.prototype.subscribeCore = function (o) {
  2372. var state = {
  2373. o: o,
  2374. self: this,
  2375. first: true,
  2376. newState: this._initialState
  2377. };
  2378. return this._s.scheduleRecursive(state, scheduleRecursive);
  2379. };
  2380. return GenerateObservable;
  2381. }(ObservableBase));
  2382. /**
  2383. * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
  2384. *
  2385. * @example
  2386. * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
  2387. * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
  2388. * @param {Mixed} initialState Initial state.
  2389. * @param {Function} condition Condition to terminate generation (upon returning false).
  2390. * @param {Function} iterate Iteration step function.
  2391. * @param {Function} resultSelector Selector function for results produced in the sequence.
  2392. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
  2393. * @returns {Observable} The generated sequence.
  2394. */
  2395. Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
  2396. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2397. return new GenerateObservable(initialState, condition, iterate, resultSelector, scheduler);
  2398. };
  2399. function observableOf (scheduler, array) {
  2400. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2401. return new FromArrayObservable(array, scheduler);
  2402. }
  2403. /**
  2404. * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
  2405. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
  2406. */
  2407. Observable.of = function () {
  2408. var len = arguments.length, args = new Array(len);
  2409. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2410. return new FromArrayObservable(args, currentThreadScheduler);
  2411. };
  2412. /**
  2413. * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
  2414. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
  2415. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
  2416. */
  2417. Observable.ofWithScheduler = function (scheduler) {
  2418. var len = arguments.length, args = new Array(len - 1);
  2419. for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
  2420. return new FromArrayObservable(args, scheduler);
  2421. };
  2422. /**
  2423. * Creates an Observable sequence from changes to an array using Array.observe.
  2424. * @param {Array} array An array to observe changes.
  2425. * @returns {Observable} An observable sequence containing changes to an array from Array.observe.
  2426. */
  2427. Observable.ofArrayChanges = function(array) {
  2428. if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); }
  2429. if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
  2430. return new AnonymousObservable(function(observer) {
  2431. function observerFn(changes) {
  2432. for(var i = 0, len = changes.length; i < len; i++) {
  2433. observer.onNext(changes[i]);
  2434. }
  2435. }
  2436. Array.observe(array, observerFn);
  2437. return function () {
  2438. Array.unobserve(array, observerFn);
  2439. };
  2440. });
  2441. };
  2442. /**
  2443. * Creates an Observable sequence from changes to an object using Object.observe.
  2444. * @param {Object} obj An object to observe changes.
  2445. * @returns {Observable} An observable sequence containing changes to an object from Object.observe.
  2446. */
  2447. Observable.ofObjectChanges = function(obj) {
  2448. if (obj == null) { throw new TypeError('object must not be null or undefined.'); }
  2449. if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') }
  2450. return new AnonymousObservable(function(observer) {
  2451. function observerFn(changes) {
  2452. for(var i = 0, len = changes.length; i < len; i++) {
  2453. observer.onNext(changes[i]);
  2454. }
  2455. }
  2456. Object.observe(obj, observerFn);
  2457. return function () {
  2458. Object.unobserve(obj, observerFn);
  2459. };
  2460. });
  2461. };
  2462. var NeverObservable = (function(__super__) {
  2463. inherits(NeverObservable, __super__);
  2464. function NeverObservable() {
  2465. __super__.call(this);
  2466. }
  2467. NeverObservable.prototype.subscribeCore = function (observer) {
  2468. return disposableEmpty;
  2469. };
  2470. return NeverObservable;
  2471. }(ObservableBase));
  2472. var NEVER_OBSERVABLE = new NeverObservable();
  2473. /**
  2474. * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
  2475. * @returns {Observable} An observable sequence whose observers will never get called.
  2476. */
  2477. var observableNever = Observable.never = function () {
  2478. return NEVER_OBSERVABLE;
  2479. };
  2480. var PairsObservable = (function(__super__) {
  2481. inherits(PairsObservable, __super__);
  2482. function PairsObservable(o, scheduler) {
  2483. this._o = o;
  2484. this._keys = Object.keys(o);
  2485. this._scheduler = scheduler;
  2486. __super__.call(this);
  2487. }
  2488. function scheduleMethod(o, obj, keys) {
  2489. return function loopRecursive(i, recurse) {
  2490. if (i < keys.length) {
  2491. var key = keys[i];
  2492. o.onNext([key, obj[key]]);
  2493. recurse(i + 1);
  2494. } else {
  2495. o.onCompleted();
  2496. }
  2497. };
  2498. }
  2499. PairsObservable.prototype.subscribeCore = function (o) {
  2500. return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._o, this._keys));
  2501. };
  2502. return PairsObservable;
  2503. }(ObservableBase));
  2504. /**
  2505. * Convert an object into an observable sequence of [key, value] pairs.
  2506. * @param {Object} obj The object to inspect.
  2507. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
  2508. * @returns {Observable} An observable sequence of [key, value] pairs from the object.
  2509. */
  2510. Observable.pairs = function (obj, scheduler) {
  2511. scheduler || (scheduler = currentThreadScheduler);
  2512. return new PairsObservable(obj, scheduler);
  2513. };
  2514. var RangeObservable = (function(__super__) {
  2515. inherits(RangeObservable, __super__);
  2516. function RangeObservable(start, count, scheduler) {
  2517. this.start = start;
  2518. this.rangeCount = count;
  2519. this.scheduler = scheduler;
  2520. __super__.call(this);
  2521. }
  2522. function loopRecursive(start, count, o) {
  2523. return function loop (i, recurse) {
  2524. if (i < count) {
  2525. o.onNext(start + i);
  2526. recurse(i + 1);
  2527. } else {
  2528. o.onCompleted();
  2529. }
  2530. };
  2531. }
  2532. RangeObservable.prototype.subscribeCore = function (o) {
  2533. return this.scheduler.scheduleRecursive(
  2534. 0,
  2535. loopRecursive(this.start, this.rangeCount, o)
  2536. );
  2537. };
  2538. return RangeObservable;
  2539. }(ObservableBase));
  2540. /**
  2541. * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
  2542. * @param {Number} start The value of the first integer in the sequence.
  2543. * @param {Number} count The number of sequential integers to generate.
  2544. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
  2545. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
  2546. */
  2547. Observable.range = function (start, count, scheduler) {
  2548. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2549. return new RangeObservable(start, count, scheduler);
  2550. };
  2551. var RepeatObservable = (function(__super__) {
  2552. inherits(RepeatObservable, __super__);
  2553. function RepeatObservable(value, repeatCount, scheduler) {
  2554. this.value = value;
  2555. this.repeatCount = repeatCount == null ? -1 : repeatCount;
  2556. this.scheduler = scheduler;
  2557. __super__.call(this);
  2558. }
  2559. RepeatObservable.prototype.subscribeCore = function (observer) {
  2560. var sink = new RepeatSink(observer, this);
  2561. return sink.run();
  2562. };
  2563. return RepeatObservable;
  2564. }(ObservableBase));
  2565. function RepeatSink(observer, parent) {
  2566. this.observer = observer;
  2567. this.parent = parent;
  2568. }
  2569. RepeatSink.prototype.run = function () {
  2570. var observer = this.observer, value = this.parent.value;
  2571. function loopRecursive(i, recurse) {
  2572. if (i === -1 || i > 0) {
  2573. observer.onNext(value);
  2574. i > 0 && i--;
  2575. }
  2576. if (i === 0) { return observer.onCompleted(); }
  2577. recurse(i);
  2578. }
  2579. return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive);
  2580. };
  2581. /**
  2582. * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
  2583. * @param {Mixed} value Element to repeat.
  2584. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
  2585. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
  2586. * @returns {Observable} An observable sequence that repeats the given element the specified number of times.
  2587. */
  2588. Observable.repeat = function (value, repeatCount, scheduler) {
  2589. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2590. return new RepeatObservable(value, repeatCount, scheduler);
  2591. };
  2592. var JustObservable = (function(__super__) {
  2593. inherits(JustObservable, __super__);
  2594. function JustObservable(value, scheduler) {
  2595. this._value = value;
  2596. this._scheduler = scheduler;
  2597. __super__.call(this);
  2598. }
  2599. JustObservable.prototype.subscribeCore = function (o) {
  2600. var state = [this._value, o];
  2601. return this._scheduler === immediateScheduler ?
  2602. scheduleItem(null, state) :
  2603. this._scheduler.schedule(state, scheduleItem);
  2604. };
  2605. function scheduleItem(s, state) {
  2606. var value = state[0], observer = state[1];
  2607. observer.onNext(value);
  2608. observer.onCompleted();
  2609. return disposableEmpty;
  2610. }
  2611. return JustObservable;
  2612. }(ObservableBase));
  2613. /**
  2614. * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
  2615. * There is an alias called 'just' or browsers <IE9.
  2616. * @param {Mixed} value Single element in the resulting observable sequence.
  2617. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
  2618. * @returns {Observable} An observable sequence containing the single specified element.
  2619. */
  2620. var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
  2621. isScheduler(scheduler) || (scheduler = immediateScheduler);
  2622. return new JustObservable(value, scheduler);
  2623. };
  2624. var ThrowObservable = (function(__super__) {
  2625. inherits(ThrowObservable, __super__);
  2626. function ThrowObservable(error, scheduler) {
  2627. this._error = error;
  2628. this._scheduler = scheduler;
  2629. __super__.call(this);
  2630. }
  2631. ThrowObservable.prototype.subscribeCore = function (o) {
  2632. var state = [this._error, o];
  2633. return this._scheduler === immediateScheduler ?
  2634. scheduleItem(null, state) :
  2635. this._scheduler.schedule(state, scheduleItem);
  2636. };
  2637. function scheduleItem(s, state) {
  2638. var e = state[0], o = state[1];
  2639. o.onError(e);
  2640. return disposableEmpty;
  2641. }
  2642. return ThrowObservable;
  2643. }(ObservableBase));
  2644. /**
  2645. * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
  2646. * There is an alias to this method called 'throwError' for browsers <IE9.
  2647. * @param {Mixed} error An object used for the sequence's termination.
  2648. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
  2649. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
  2650. */
  2651. var observableThrow = Observable['throw'] = function (error, scheduler) {
  2652. isScheduler(scheduler) || (scheduler = immediateScheduler);
  2653. return new ThrowObservable(error, scheduler);
  2654. };
  2655. var UsingObservable = (function (__super__) {
  2656. inherits(UsingObservable, __super__);
  2657. function UsingObservable(resFn, obsFn) {
  2658. this._resFn = resFn;
  2659. this._obsFn = obsFn;
  2660. __super__.call(this);
  2661. }
  2662. UsingObservable.prototype.subscribeCore = function (o) {
  2663. var disposable = disposableEmpty;
  2664. var resource = tryCatch(this._resFn)();
  2665. if (resource === errorObj) {
  2666. return new BinaryDisposable(observableThrow(resource.e).subscribe(o), disposable);
  2667. }
  2668. resource && (disposable = resource);
  2669. var source = tryCatch(this._obsFn)(resource);
  2670. if (source === errorObj) {
  2671. return new BinaryDisposable(observableThrow(source.e).subscribe(o), disposable);
  2672. }
  2673. return new BinaryDisposable(source.subscribe(o), disposable);
  2674. };
  2675. return UsingObservable;
  2676. }(ObservableBase));
  2677. /**
  2678. * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
  2679. * @param {Function} resourceFactory Factory function to obtain a resource object.
  2680. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
  2681. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
  2682. */
  2683. Observable.using = function (resourceFactory, observableFactory) {
  2684. return new UsingObservable(resourceFactory, observableFactory);
  2685. };
  2686. /**
  2687. * Propagates the observable sequence or Promise that reacts first.
  2688. * @param {Observable} rightSource Second observable sequence or Promise.
  2689. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
  2690. */
  2691. observableProto.amb = function (rightSource) {
  2692. var leftSource = this;
  2693. return new AnonymousObservable(function (observer) {
  2694. var choice,
  2695. leftChoice = 'L', rightChoice = 'R',
  2696. leftSubscription = new SingleAssignmentDisposable(),
  2697. rightSubscription = new SingleAssignmentDisposable();
  2698. isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
  2699. function choiceL() {
  2700. if (!choice) {
  2701. choice = leftChoice;
  2702. rightSubscription.dispose();
  2703. }
  2704. }
  2705. function choiceR() {
  2706. if (!choice) {
  2707. choice = rightChoice;
  2708. leftSubscription.dispose();
  2709. }
  2710. }
  2711. var leftSubscribe = observerCreate(
  2712. function (left) {
  2713. choiceL();
  2714. choice === leftChoice && observer.onNext(left);
  2715. },
  2716. function (e) {
  2717. choiceL();
  2718. choice === leftChoice && observer.onError(e);
  2719. },
  2720. function () {
  2721. choiceL();
  2722. choice === leftChoice && observer.onCompleted();
  2723. }
  2724. );
  2725. var rightSubscribe = observerCreate(
  2726. function (right) {
  2727. choiceR();
  2728. choice === rightChoice && observer.onNext(right);
  2729. },
  2730. function (e) {
  2731. choiceR();
  2732. choice === rightChoice && observer.onError(e);
  2733. },
  2734. function () {
  2735. choiceR();
  2736. choice === rightChoice && observer.onCompleted();
  2737. }
  2738. );
  2739. leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
  2740. rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));
  2741. return new BinaryDisposable(leftSubscription, rightSubscription);
  2742. });
  2743. };
  2744. function amb(p, c) { return p.amb(c); }
  2745. /**
  2746. * Propagates the observable sequence or Promise that reacts first.
  2747. * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
  2748. */
  2749. Observable.amb = function () {
  2750. var acc = observableNever(), items;
  2751. if (Array.isArray(arguments[0])) {
  2752. items = arguments[0];
  2753. } else {
  2754. var len = arguments.length;
  2755. items = new Array(items);
  2756. for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
  2757. }
  2758. for (var i = 0, len = items.length; i < len; i++) {
  2759. acc = amb(acc, items[i]);
  2760. }
  2761. return acc;
  2762. };
  2763. var CatchObservable = (function (__super__) {
  2764. inherits(CatchObservable, __super__);
  2765. function CatchObservable(source, fn) {
  2766. this.source = source;
  2767. this._fn = fn;
  2768. __super__.call(this);
  2769. }
  2770. CatchObservable.prototype.subscribeCore = function (o) {
  2771. var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
  2772. subscription.setDisposable(d1);
  2773. d1.setDisposable(this.source.subscribe(new CatchObserver(o, subscription, this._fn)));
  2774. return subscription;
  2775. };
  2776. return CatchObservable;
  2777. }(ObservableBase));
  2778. var CatchObserver = (function(__super__) {
  2779. inherits(CatchObserver, __super__);
  2780. function CatchObserver(o, s, fn) {
  2781. this._o = o;
  2782. this._s = s;
  2783. this._fn = fn;
  2784. __super__.call(this);
  2785. }
  2786. CatchObserver.prototype.next = function (x) { this._o.onNext(x); };
  2787. CatchObserver.prototype.completed = function () { return this._o.onCompleted(); };
  2788. CatchObserver.prototype.error = function (e) {
  2789. var result = tryCatch(this._fn)(e);
  2790. if (result === errorObj) { return this._o.onError(result.e); }
  2791. isPromise(result) && (result = observableFromPromise(result));
  2792. var d = new SingleAssignmentDisposable();
  2793. this._s.setDisposable(d);
  2794. d.setDisposable(result.subscribe(this._o));
  2795. };
  2796. return CatchObserver;
  2797. }(AbstractObserver));
  2798. /**
  2799. * Continues an observable sequence that is terminated by an exception with the next observable sequence.
  2800. * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
  2801. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
  2802. */
  2803. observableProto['catch'] = function (handlerOrSecond) {
  2804. return isFunction(handlerOrSecond) ? new CatchObservable(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]);
  2805. };
  2806. /**
  2807. * Continues an observable sequence that is terminated by an exception with the next observable sequence.
  2808. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
  2809. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
  2810. */
  2811. var observableCatch = Observable['catch'] = function () {
  2812. var items;
  2813. if (Array.isArray(arguments[0])) {
  2814. items = arguments[0];
  2815. } else {
  2816. var len = arguments.length;
  2817. items = new Array(len);
  2818. for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
  2819. }
  2820. return enumerableOf(items).catchError();
  2821. };
  2822. /**
  2823. * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
  2824. * This can be in the form of an argument list of observables or an array.
  2825. *
  2826. * @example
  2827. * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
  2828. * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
  2829. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  2830. */
  2831. observableProto.combineLatest = function () {
  2832. var len = arguments.length, args = new Array(len);
  2833. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2834. if (Array.isArray(args[0])) {
  2835. args[0].unshift(this);
  2836. } else {
  2837. args.unshift(this);
  2838. }
  2839. return combineLatest.apply(this, args);
  2840. };
  2841. function falseFactory() { return false; }
  2842. function argumentsToArray() {
  2843. var len = arguments.length, args = new Array(len);
  2844. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2845. return args;
  2846. }
  2847. var CombineLatestObservable = (function(__super__) {
  2848. inherits(CombineLatestObservable, __super__);
  2849. function CombineLatestObservable(params, cb) {
  2850. this._params = params;
  2851. this._cb = cb;
  2852. __super__.call(this);
  2853. }
  2854. CombineLatestObservable.prototype.subscribeCore = function(observer) {
  2855. var len = this._params.length,
  2856. subscriptions = new Array(len);
  2857. var state = {
  2858. hasValue: arrayInitialize(len, falseFactory),
  2859. hasValueAll: false,
  2860. isDone: arrayInitialize(len, falseFactory),
  2861. values: new Array(len)
  2862. };
  2863. for (var i = 0; i < len; i++) {
  2864. var source = this._params[i], sad = new SingleAssignmentDisposable();
  2865. subscriptions[i] = sad;
  2866. isPromise(source) && (source = observableFromPromise(source));
  2867. sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this._cb, state)));
  2868. }
  2869. return new NAryDisposable(subscriptions);
  2870. };
  2871. return CombineLatestObservable;
  2872. }(ObservableBase));
  2873. var CombineLatestObserver = (function (__super__) {
  2874. inherits(CombineLatestObserver, __super__);
  2875. function CombineLatestObserver(o, i, cb, state) {
  2876. this._o = o;
  2877. this._i = i;
  2878. this._cb = cb;
  2879. this._state = state;
  2880. __super__.call(this);
  2881. }
  2882. function notTheSame(i) {
  2883. return function (x, j) {
  2884. return j !== i;
  2885. };
  2886. }
  2887. CombineLatestObserver.prototype.next = function (x) {
  2888. this._state.values[this._i] = x;
  2889. this._state.hasValue[this._i] = true;
  2890. if (this._state.hasValueAll || (this._state.hasValueAll = this._state.hasValue.every(identity))) {
  2891. var res = tryCatch(this._cb).apply(null, this._state.values);
  2892. if (res === errorObj) { return this._o.onError(res.e); }
  2893. this._o.onNext(res);
  2894. } else if (this._state.isDone.filter(notTheSame(this._i)).every(identity)) {
  2895. this._o.onCompleted();
  2896. }
  2897. };
  2898. CombineLatestObserver.prototype.error = function (e) {
  2899. this._o.onError(e);
  2900. };
  2901. CombineLatestObserver.prototype.completed = function () {
  2902. this._state.isDone[this._i] = true;
  2903. this._state.isDone.every(identity) && this._o.onCompleted();
  2904. };
  2905. return CombineLatestObserver;
  2906. }(AbstractObserver));
  2907. /**
  2908. * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
  2909. *
  2910. * @example
  2911. * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
  2912. * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
  2913. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  2914. */
  2915. var combineLatest = Observable.combineLatest = function () {
  2916. var len = arguments.length, args = new Array(len);
  2917. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2918. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  2919. Array.isArray(args[0]) && (args = args[0]);
  2920. return new CombineLatestObservable(args, resultSelector);
  2921. };
  2922. /**
  2923. * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
  2924. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
  2925. */
  2926. observableProto.concat = function () {
  2927. for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
  2928. args.unshift(this);
  2929. return observableConcat.apply(null, args);
  2930. };
  2931. var ConcatObserver = (function(__super__) {
  2932. inherits(ConcatObserver, __super__);
  2933. function ConcatObserver(s, fn) {
  2934. this._s = s;
  2935. this._fn = fn;
  2936. __super__.call(this);
  2937. }
  2938. ConcatObserver.prototype.next = function (x) { this._s.o.onNext(x); };
  2939. ConcatObserver.prototype.error = function (e) { this._s.o.onError(e); };
  2940. ConcatObserver.prototype.completed = function () { this._s.i++; this._fn(this._s); };
  2941. return ConcatObserver;
  2942. }(AbstractObserver));
  2943. var ConcatObservable = (function(__super__) {
  2944. inherits(ConcatObservable, __super__);
  2945. function ConcatObservable(sources) {
  2946. this._sources = sources;
  2947. __super__.call(this);
  2948. }
  2949. function scheduleRecursive (state, recurse) {
  2950. if (state.disposable.isDisposed) { return; }
  2951. if (state.i === state.sources.length) { return state.o.onCompleted(); }
  2952. // Check if promise
  2953. var currentValue = state.sources[state.i];
  2954. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  2955. var d = new SingleAssignmentDisposable();
  2956. state.subscription.setDisposable(d);
  2957. d.setDisposable(currentValue.subscribe(new ConcatObserver(state, recurse)));
  2958. }
  2959. ConcatObservable.prototype.subscribeCore = function(o) {
  2960. var subscription = new SerialDisposable();
  2961. var disposable = disposableCreate(noop);
  2962. var state = {
  2963. o: o,
  2964. i: 0,
  2965. subscription: subscription,
  2966. disposable: disposable,
  2967. sources: this._sources
  2968. };
  2969. var cancelable = immediateScheduler.scheduleRecursive(state, scheduleRecursive);
  2970. return new NAryDisposable([subscription, disposable, cancelable]);
  2971. };
  2972. return ConcatObservable;
  2973. }(ObservableBase));
  2974. /**
  2975. * Concatenates all the observable sequences.
  2976. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
  2977. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
  2978. */
  2979. var observableConcat = Observable.concat = function () {
  2980. var args;
  2981. if (Array.isArray(arguments[0])) {
  2982. args = arguments[0];
  2983. } else {
  2984. args = new Array(arguments.length);
  2985. for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
  2986. }
  2987. return new ConcatObservable(args);
  2988. };
  2989. /**
  2990. * Concatenates an observable sequence of observable sequences.
  2991. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
  2992. */
  2993. observableProto.concatAll = function () {
  2994. return this.merge(1);
  2995. };
  2996. var MergeObservable = (function (__super__) {
  2997. inherits(MergeObservable, __super__);
  2998. function MergeObservable(source, maxConcurrent) {
  2999. this.source = source;
  3000. this.maxConcurrent = maxConcurrent;
  3001. __super__.call(this);
  3002. }
  3003. MergeObservable.prototype.subscribeCore = function(observer) {
  3004. var g = new CompositeDisposable();
  3005. g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
  3006. return g;
  3007. };
  3008. return MergeObservable;
  3009. }(ObservableBase));
  3010. var MergeObserver = (function (__super__) {
  3011. function MergeObserver(o, max, g) {
  3012. this.o = o;
  3013. this.max = max;
  3014. this.g = g;
  3015. this.done = false;
  3016. this.q = [];
  3017. this.activeCount = 0;
  3018. __super__.call(this);
  3019. }
  3020. inherits(MergeObserver, __super__);
  3021. MergeObserver.prototype.handleSubscribe = function (xs) {
  3022. var sad = new SingleAssignmentDisposable();
  3023. this.g.add(sad);
  3024. isPromise(xs) && (xs = observableFromPromise(xs));
  3025. sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
  3026. };
  3027. MergeObserver.prototype.next = function (innerSource) {
  3028. if(this.activeCount < this.max) {
  3029. this.activeCount++;
  3030. this.handleSubscribe(innerSource);
  3031. } else {
  3032. this.q.push(innerSource);
  3033. }
  3034. };
  3035. MergeObserver.prototype.error = function (e) { this.o.onError(e); };
  3036. MergeObserver.prototype.completed = function () { this.done = true; this.activeCount === 0 && this.o.onCompleted(); };
  3037. function InnerObserver(parent, sad) {
  3038. this.parent = parent;
  3039. this.sad = sad;
  3040. __super__.call(this);
  3041. }
  3042. inherits(InnerObserver, __super__);
  3043. InnerObserver.prototype.next = function (x) { this.parent.o.onNext(x); };
  3044. InnerObserver.prototype.error = function (e) { this.parent.o.onError(e); };
  3045. InnerObserver.prototype.completed = function () {
  3046. this.parent.g.remove(this.sad);
  3047. if (this.parent.q.length > 0) {
  3048. this.parent.handleSubscribe(this.parent.q.shift());
  3049. } else {
  3050. this.parent.activeCount--;
  3051. this.parent.done && this.parent.activeCount === 0 && this.parent.o.onCompleted();
  3052. }
  3053. };
  3054. return MergeObserver;
  3055. }(AbstractObserver));
  3056. /**
  3057. * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
  3058. * Or merges two observable sequences into a single observable sequence.
  3059. * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
  3060. * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
  3061. */
  3062. observableProto.merge = function (maxConcurrentOrOther) {
  3063. return typeof maxConcurrentOrOther !== 'number' ?
  3064. observableMerge(this, maxConcurrentOrOther) :
  3065. new MergeObservable(this, maxConcurrentOrOther);
  3066. };
  3067. /**
  3068. * Merges all the observable sequences into a single observable sequence.
  3069. * The scheduler is optional and if not specified, the immediate scheduler is used.
  3070. * @returns {Observable} The observable sequence that merges the elements of the observable sequences.
  3071. */
  3072. var observableMerge = Observable.merge = function () {
  3073. var scheduler, sources = [], i, len = arguments.length;
  3074. if (!arguments[0]) {
  3075. scheduler = immediateScheduler;
  3076. for(i = 1; i < len; i++) { sources.push(arguments[i]); }
  3077. } else if (isScheduler(arguments[0])) {
  3078. scheduler = arguments[0];
  3079. for(i = 1; i < len; i++) { sources.push(arguments[i]); }
  3080. } else {
  3081. scheduler = immediateScheduler;
  3082. for(i = 0; i < len; i++) { sources.push(arguments[i]); }
  3083. }
  3084. if (Array.isArray(sources[0])) {
  3085. sources = sources[0];
  3086. }
  3087. return observableOf(scheduler, sources).mergeAll();
  3088. };
  3089. var MergeAllObservable = (function (__super__) {
  3090. inherits(MergeAllObservable, __super__);
  3091. function MergeAllObservable(source) {
  3092. this.source = source;
  3093. __super__.call(this);
  3094. }
  3095. MergeAllObservable.prototype.subscribeCore = function (o) {
  3096. var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
  3097. g.add(m);
  3098. m.setDisposable(this.source.subscribe(new MergeAllObserver(o, g)));
  3099. return g;
  3100. };
  3101. return MergeAllObservable;
  3102. }(ObservableBase));
  3103. var MergeAllObserver = (function (__super__) {
  3104. function MergeAllObserver(o, g) {
  3105. this.o = o;
  3106. this.g = g;
  3107. this.done = false;
  3108. __super__.call(this);
  3109. }
  3110. inherits(MergeAllObserver, __super__);
  3111. MergeAllObserver.prototype.next = function(innerSource) {
  3112. var sad = new SingleAssignmentDisposable();
  3113. this.g.add(sad);
  3114. isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
  3115. sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad)));
  3116. };
  3117. MergeAllObserver.prototype.error = function (e) {
  3118. this.o.onError(e);
  3119. };
  3120. MergeAllObserver.prototype.completed = function () {
  3121. this.done = true;
  3122. this.g.length === 1 && this.o.onCompleted();
  3123. };
  3124. function InnerObserver(parent, sad) {
  3125. this.parent = parent;
  3126. this.sad = sad;
  3127. __super__.call(this);
  3128. }
  3129. inherits(InnerObserver, __super__);
  3130. InnerObserver.prototype.next = function (x) {
  3131. this.parent.o.onNext(x);
  3132. };
  3133. InnerObserver.prototype.error = function (e) {
  3134. this.parent.o.onError(e);
  3135. };
  3136. InnerObserver.prototype.completed = function () {
  3137. this.parent.g.remove(this.sad);
  3138. this.parent.done && this.parent.g.length === 1 && this.parent.o.onCompleted();
  3139. };
  3140. return MergeAllObserver;
  3141. }(AbstractObserver));
  3142. /**
  3143. * Merges an observable sequence of observable sequences into an observable sequence.
  3144. * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
  3145. */
  3146. observableProto.mergeAll = function () {
  3147. return new MergeAllObservable(this);
  3148. };
  3149. var CompositeError = Rx.CompositeError = function(errors) {
  3150. this.innerErrors = errors;
  3151. this.message = 'This contains multiple errors. Check the innerErrors';
  3152. Error.call(this);
  3153. };
  3154. CompositeError.prototype = Object.create(Error.prototype);
  3155. CompositeError.prototype.name = 'CompositeError';
  3156. var MergeDelayErrorObservable = (function(__super__) {
  3157. inherits(MergeDelayErrorObservable, __super__);
  3158. function MergeDelayErrorObservable(source) {
  3159. this.source = source;
  3160. __super__.call(this);
  3161. }
  3162. MergeDelayErrorObservable.prototype.subscribeCore = function (o) {
  3163. var group = new CompositeDisposable(),
  3164. m = new SingleAssignmentDisposable(),
  3165. state = { isStopped: false, errors: [], o: o };
  3166. group.add(m);
  3167. m.setDisposable(this.source.subscribe(new MergeDelayErrorObserver(group, state)));
  3168. return group;
  3169. };
  3170. return MergeDelayErrorObservable;
  3171. }(ObservableBase));
  3172. var MergeDelayErrorObserver = (function(__super__) {
  3173. inherits(MergeDelayErrorObserver, __super__);
  3174. function MergeDelayErrorObserver(group, state) {
  3175. this._group = group;
  3176. this._state = state;
  3177. __super__.call(this);
  3178. }
  3179. function setCompletion(o, errors) {
  3180. if (errors.length === 0) {
  3181. o.onCompleted();
  3182. } else if (errors.length === 1) {
  3183. o.onError(errors[0]);
  3184. } else {
  3185. o.onError(new CompositeError(errors));
  3186. }
  3187. }
  3188. MergeDelayErrorObserver.prototype.next = function (x) {
  3189. var inner = new SingleAssignmentDisposable();
  3190. this._group.add(inner);
  3191. // Check for promises support
  3192. isPromise(x) && (x = observableFromPromise(x));
  3193. inner.setDisposable(x.subscribe(new InnerObserver(inner, this._group, this._state)));
  3194. };
  3195. MergeDelayErrorObserver.prototype.error = function (e) {
  3196. this._state.errors.push(e);
  3197. this._state.isStopped = true;
  3198. this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  3199. };
  3200. MergeDelayErrorObserver.prototype.completed = function () {
  3201. this._state.isStopped = true;
  3202. this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  3203. };
  3204. inherits(InnerObserver, __super__);
  3205. function InnerObserver(inner, group, state) {
  3206. this._inner = inner;
  3207. this._group = group;
  3208. this._state = state;
  3209. __super__.call(this);
  3210. }
  3211. InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  3212. InnerObserver.prototype.error = function (e) {
  3213. this._state.errors.push(e);
  3214. this._group.remove(this._inner);
  3215. this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  3216. };
  3217. InnerObserver.prototype.completed = function () {
  3218. this._group.remove(this._inner);
  3219. this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  3220. };
  3221. return MergeDelayErrorObserver;
  3222. }(AbstractObserver));
  3223. /**
  3224. * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
  3225. * receive all successfully emitted items from all of the source Observables without being interrupted by
  3226. * an error notification from one of them.
  3227. *
  3228. * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
  3229. * error via the Observer's onError, mergeDelayError will refrain from propagating that
  3230. * error notification until all of the merged Observables have finished emitting items.
  3231. * @param {Array | Arguments} args Arguments or an array to merge.
  3232. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
  3233. */
  3234. Observable.mergeDelayError = function() {
  3235. var args;
  3236. if (Array.isArray(arguments[0])) {
  3237. args = arguments[0];
  3238. } else {
  3239. var len = arguments.length;
  3240. args = new Array(len);
  3241. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3242. }
  3243. var source = observableOf(null, args);
  3244. return new MergeDelayErrorObservable(source);
  3245. };
  3246. /**
  3247. * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
  3248. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
  3249. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
  3250. */
  3251. observableProto.onErrorResumeNext = function (second) {
  3252. if (!second) { throw new Error('Second observable is required'); }
  3253. return onErrorResumeNext([this, second]);
  3254. };
  3255. var OnErrorResumeNextObservable = (function(__super__) {
  3256. inherits(OnErrorResumeNextObservable, __super__);
  3257. function OnErrorResumeNextObservable(sources) {
  3258. this.sources = sources;
  3259. __super__.call(this);
  3260. }
  3261. function scheduleMethod(state, recurse) {
  3262. if (state.pos < state.sources.length) {
  3263. var current = state.sources[state.pos++];
  3264. isPromise(current) && (current = observableFromPromise(current));
  3265. var d = new SingleAssignmentDisposable();
  3266. state.subscription.setDisposable(d);
  3267. d.setDisposable(current.subscribe(new OnErrorResumeNextObserver(state, recurse)));
  3268. } else {
  3269. state.o.onCompleted();
  3270. }
  3271. }
  3272. OnErrorResumeNextObservable.prototype.subscribeCore = function (o) {
  3273. var subscription = new SerialDisposable(),
  3274. state = {pos: 0, subscription: subscription, o: o, sources: this.sources },
  3275. cancellable = immediateScheduler.scheduleRecursive(state, scheduleMethod);
  3276. return new BinaryDisposable(subscription, cancellable);
  3277. };
  3278. return OnErrorResumeNextObservable;
  3279. }(ObservableBase));
  3280. var OnErrorResumeNextObserver = (function(__super__) {
  3281. inherits(OnErrorResumeNextObserver, __super__);
  3282. function OnErrorResumeNextObserver(state, recurse) {
  3283. this._state = state;
  3284. this._recurse = recurse;
  3285. __super__.call(this);
  3286. }
  3287. OnErrorResumeNextObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  3288. OnErrorResumeNextObserver.prototype.error = function () { this._recurse(this._state); };
  3289. OnErrorResumeNextObserver.prototype.completed = function () { this._recurse(this._state); };
  3290. return OnErrorResumeNextObserver;
  3291. }(AbstractObserver));
  3292. /**
  3293. * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
  3294. * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
  3295. */
  3296. var onErrorResumeNext = Observable.onErrorResumeNext = function () {
  3297. var sources = [];
  3298. if (Array.isArray(arguments[0])) {
  3299. sources = arguments[0];
  3300. } else {
  3301. var len = arguments.length;
  3302. sources = new Array(len);
  3303. for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
  3304. }
  3305. return new OnErrorResumeNextObservable(sources);
  3306. };
  3307. var SkipUntilObservable = (function(__super__) {
  3308. inherits(SkipUntilObservable, __super__);
  3309. function SkipUntilObservable(source, other) {
  3310. this._s = source;
  3311. this._o = isPromise(other) ? observableFromPromise(other) : other;
  3312. this._open = false;
  3313. __super__.call(this);
  3314. }
  3315. SkipUntilObservable.prototype.subscribeCore = function(o) {
  3316. var leftSubscription = new SingleAssignmentDisposable();
  3317. leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this)));
  3318. isPromise(this._o) && (this._o = observableFromPromise(this._o));
  3319. var rightSubscription = new SingleAssignmentDisposable();
  3320. rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription)));
  3321. return new BinaryDisposable(leftSubscription, rightSubscription);
  3322. };
  3323. return SkipUntilObservable;
  3324. }(ObservableBase));
  3325. var SkipUntilSourceObserver = (function(__super__) {
  3326. inherits(SkipUntilSourceObserver, __super__);
  3327. function SkipUntilSourceObserver(o, p) {
  3328. this._o = o;
  3329. this._p = p;
  3330. __super__.call(this);
  3331. }
  3332. SkipUntilSourceObserver.prototype.next = function (x) {
  3333. this._p._open && this._o.onNext(x);
  3334. };
  3335. SkipUntilSourceObserver.prototype.error = function (err) {
  3336. this._o.onError(err);
  3337. };
  3338. SkipUntilSourceObserver.prototype.onCompleted = function () {
  3339. this._p._open && this._o.onCompleted();
  3340. };
  3341. return SkipUntilSourceObserver;
  3342. }(AbstractObserver));
  3343. var SkipUntilOtherObserver = (function(__super__) {
  3344. inherits(SkipUntilOtherObserver, __super__);
  3345. function SkipUntilOtherObserver(o, p, r) {
  3346. this._o = o;
  3347. this._p = p;
  3348. this._r = r;
  3349. __super__.call(this);
  3350. }
  3351. SkipUntilOtherObserver.prototype.next = function () {
  3352. this._p._open = true;
  3353. this._r.dispose();
  3354. };
  3355. SkipUntilOtherObserver.prototype.error = function (err) {
  3356. this._o.onError(err);
  3357. };
  3358. SkipUntilOtherObserver.prototype.onCompleted = function () {
  3359. this._r.dispose();
  3360. };
  3361. return SkipUntilOtherObserver;
  3362. }(AbstractObserver));
  3363. /**
  3364. * Returns the values from the source observable sequence only after the other observable sequence produces a value.
  3365. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
  3366. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
  3367. */
  3368. observableProto.skipUntil = function (other) {
  3369. return new SkipUntilObservable(this, other);
  3370. };
  3371. var SwitchObservable = (function(__super__) {
  3372. inherits(SwitchObservable, __super__);
  3373. function SwitchObservable(source) {
  3374. this.source = source;
  3375. __super__.call(this);
  3376. }
  3377. SwitchObservable.prototype.subscribeCore = function (o) {
  3378. var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
  3379. return new BinaryDisposable(s, inner);
  3380. };
  3381. inherits(SwitchObserver, AbstractObserver);
  3382. function SwitchObserver(o, inner) {
  3383. this.o = o;
  3384. this.inner = inner;
  3385. this.stopped = false;
  3386. this.latest = 0;
  3387. this.hasLatest = false;
  3388. AbstractObserver.call(this);
  3389. }
  3390. SwitchObserver.prototype.next = function (innerSource) {
  3391. var d = new SingleAssignmentDisposable(), id = ++this.latest;
  3392. this.hasLatest = true;
  3393. this.inner.setDisposable(d);
  3394. isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
  3395. d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
  3396. };
  3397. SwitchObserver.prototype.error = function (e) {
  3398. this.o.onError(e);
  3399. };
  3400. SwitchObserver.prototype.completed = function () {
  3401. this.stopped = true;
  3402. !this.hasLatest && this.o.onCompleted();
  3403. };
  3404. inherits(InnerObserver, AbstractObserver);
  3405. function InnerObserver(parent, id) {
  3406. this.parent = parent;
  3407. this.id = id;
  3408. AbstractObserver.call(this);
  3409. }
  3410. InnerObserver.prototype.next = function (x) {
  3411. this.parent.latest === this.id && this.parent.o.onNext(x);
  3412. };
  3413. InnerObserver.prototype.error = function (e) {
  3414. this.parent.latest === this.id && this.parent.o.onError(e);
  3415. };
  3416. InnerObserver.prototype.completed = function () {
  3417. if (this.parent.latest === this.id) {
  3418. this.parent.hasLatest = false;
  3419. this.parent.stopped && this.parent.o.onCompleted();
  3420. }
  3421. };
  3422. return SwitchObservable;
  3423. }(ObservableBase));
  3424. /**
  3425. * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
  3426. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
  3427. */
  3428. observableProto['switch'] = observableProto.switchLatest = function () {
  3429. return new SwitchObservable(this);
  3430. };
  3431. var TakeUntilObservable = (function(__super__) {
  3432. inherits(TakeUntilObservable, __super__);
  3433. function TakeUntilObservable(source, other) {
  3434. this.source = source;
  3435. this.other = isPromise(other) ? observableFromPromise(other) : other;
  3436. __super__.call(this);
  3437. }
  3438. TakeUntilObservable.prototype.subscribeCore = function(o) {
  3439. return new BinaryDisposable(
  3440. this.source.subscribe(o),
  3441. this.other.subscribe(new TakeUntilObserver(o))
  3442. );
  3443. };
  3444. return TakeUntilObservable;
  3445. }(ObservableBase));
  3446. var TakeUntilObserver = (function(__super__) {
  3447. inherits(TakeUntilObserver, __super__);
  3448. function TakeUntilObserver(o) {
  3449. this._o = o;
  3450. __super__.call(this);
  3451. }
  3452. TakeUntilObserver.prototype.next = function () {
  3453. this._o.onCompleted();
  3454. };
  3455. TakeUntilObserver.prototype.error = function (err) {
  3456. this._o.onError(err);
  3457. };
  3458. TakeUntilObserver.prototype.onCompleted = noop;
  3459. return TakeUntilObserver;
  3460. }(AbstractObserver));
  3461. /**
  3462. * Returns the values from the source observable sequence until the other observable sequence produces a value.
  3463. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
  3464. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
  3465. */
  3466. observableProto.takeUntil = function (other) {
  3467. return new TakeUntilObservable(this, other);
  3468. };
  3469. function falseFactory() { return false; }
  3470. function argumentsToArray() {
  3471. var len = arguments.length, args = new Array(len);
  3472. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3473. return args;
  3474. }
  3475. var WithLatestFromObservable = (function(__super__) {
  3476. inherits(WithLatestFromObservable, __super__);
  3477. function WithLatestFromObservable(source, sources, resultSelector) {
  3478. this._s = source;
  3479. this._ss = sources;
  3480. this._cb = resultSelector;
  3481. __super__.call(this);
  3482. }
  3483. WithLatestFromObservable.prototype.subscribeCore = function (o) {
  3484. var len = this._ss.length;
  3485. var state = {
  3486. hasValue: arrayInitialize(len, falseFactory),
  3487. hasValueAll: false,
  3488. values: new Array(len)
  3489. };
  3490. var n = this._ss.length, subscriptions = new Array(n + 1);
  3491. for (var i = 0; i < n; i++) {
  3492. var other = this._ss[i], sad = new SingleAssignmentDisposable();
  3493. isPromise(other) && (other = observableFromPromise(other));
  3494. sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, state)));
  3495. subscriptions[i] = sad;
  3496. }
  3497. var outerSad = new SingleAssignmentDisposable();
  3498. outerSad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this._cb, state)));
  3499. subscriptions[n] = outerSad;
  3500. return new NAryDisposable(subscriptions);
  3501. };
  3502. return WithLatestFromObservable;
  3503. }(ObservableBase));
  3504. var WithLatestFromOtherObserver = (function (__super__) {
  3505. inherits(WithLatestFromOtherObserver, __super__);
  3506. function WithLatestFromOtherObserver(o, i, state) {
  3507. this._o = o;
  3508. this._i = i;
  3509. this._state = state;
  3510. __super__.call(this);
  3511. }
  3512. WithLatestFromOtherObserver.prototype.next = function (x) {
  3513. this._state.values[this._i] = x;
  3514. this._state.hasValue[this._i] = true;
  3515. this._state.hasValueAll = this._state.hasValue.every(identity);
  3516. };
  3517. WithLatestFromOtherObserver.prototype.error = function (e) {
  3518. this._o.onError(e);
  3519. };
  3520. WithLatestFromOtherObserver.prototype.completed = noop;
  3521. return WithLatestFromOtherObserver;
  3522. }(AbstractObserver));
  3523. var WithLatestFromSourceObserver = (function (__super__) {
  3524. inherits(WithLatestFromSourceObserver, __super__);
  3525. function WithLatestFromSourceObserver(o, cb, state) {
  3526. this._o = o;
  3527. this._cb = cb;
  3528. this._state = state;
  3529. __super__.call(this);
  3530. }
  3531. WithLatestFromSourceObserver.prototype.next = function (x) {
  3532. var allValues = [x].concat(this._state.values);
  3533. if (!this._state.hasValueAll) { return; }
  3534. var res = tryCatch(this._cb).apply(null, allValues);
  3535. if (res === errorObj) { return this._o.onError(res.e); }
  3536. this._o.onNext(res);
  3537. };
  3538. WithLatestFromSourceObserver.prototype.error = function (e) {
  3539. this._o.onError(e);
  3540. };
  3541. WithLatestFromSourceObserver.prototype.completed = function () {
  3542. this._o.onCompleted();
  3543. };
  3544. return WithLatestFromSourceObserver;
  3545. }(AbstractObserver));
  3546. /**
  3547. * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
  3548. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  3549. */
  3550. observableProto.withLatestFrom = function () {
  3551. if (arguments.length === 0) { throw new Error('invalid arguments'); }
  3552. var len = arguments.length, args = new Array(len);
  3553. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3554. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  3555. Array.isArray(args[0]) && (args = args[0]);
  3556. return new WithLatestFromObservable(this, args, resultSelector);
  3557. };
  3558. function falseFactory() { return false; }
  3559. function emptyArrayFactory() { return []; }
  3560. var ZipObservable = (function(__super__) {
  3561. inherits(ZipObservable, __super__);
  3562. function ZipObservable(sources, resultSelector) {
  3563. this._s = sources;
  3564. this._cb = resultSelector;
  3565. __super__.call(this);
  3566. }
  3567. ZipObservable.prototype.subscribeCore = function(observer) {
  3568. var n = this._s.length,
  3569. subscriptions = new Array(n),
  3570. done = arrayInitialize(n, falseFactory),
  3571. q = arrayInitialize(n, emptyArrayFactory);
  3572. for (var i = 0; i < n; i++) {
  3573. var source = this._s[i], sad = new SingleAssignmentDisposable();
  3574. subscriptions[i] = sad;
  3575. isPromise(source) && (source = observableFromPromise(source));
  3576. sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this, q, done)));
  3577. }
  3578. return new NAryDisposable(subscriptions);
  3579. };
  3580. return ZipObservable;
  3581. }(ObservableBase));
  3582. var ZipObserver = (function (__super__) {
  3583. inherits(ZipObserver, __super__);
  3584. function ZipObserver(o, i, p, q, d) {
  3585. this._o = o;
  3586. this._i = i;
  3587. this._p = p;
  3588. this._q = q;
  3589. this._d = d;
  3590. __super__.call(this);
  3591. }
  3592. function notEmpty(x) { return x.length > 0; }
  3593. function shiftEach(x) { return x.shift(); }
  3594. function notTheSame(i) {
  3595. return function (x, j) {
  3596. return j !== i;
  3597. };
  3598. }
  3599. ZipObserver.prototype.next = function (x) {
  3600. this._q[this._i].push(x);
  3601. if (this._q.every(notEmpty)) {
  3602. var queuedValues = this._q.map(shiftEach);
  3603. var res = tryCatch(this._p._cb).apply(null, queuedValues);
  3604. if (res === errorObj) { return this._o.onError(res.e); }
  3605. this._o.onNext(res);
  3606. } else if (this._d.filter(notTheSame(this._i)).every(identity)) {
  3607. this._o.onCompleted();
  3608. }
  3609. };
  3610. ZipObserver.prototype.error = function (e) {
  3611. this._o.onError(e);
  3612. };
  3613. ZipObserver.prototype.completed = function () {
  3614. this._d[this._i] = true;
  3615. this._d.every(identity) && this._o.onCompleted();
  3616. };
  3617. return ZipObserver;
  3618. }(AbstractObserver));
  3619. /**
  3620. * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
  3621. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
  3622. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
  3623. */
  3624. observableProto.zip = function () {
  3625. if (arguments.length === 0) { throw new Error('invalid arguments'); }
  3626. var len = arguments.length, args = new Array(len);
  3627. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3628. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  3629. Array.isArray(args[0]) && (args = args[0]);
  3630. var parent = this;
  3631. args.unshift(parent);
  3632. return new ZipObservable(args, resultSelector);
  3633. };
  3634. /**
  3635. * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
  3636. * @param arguments Observable sources.
  3637. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
  3638. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  3639. */
  3640. Observable.zip = function () {
  3641. var len = arguments.length, args = new Array(len);
  3642. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3643. if (Array.isArray(args[0])) {
  3644. args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0];
  3645. }
  3646. var first = args.shift();
  3647. return first.zip.apply(first, args);
  3648. };
  3649. function falseFactory() { return false; }
  3650. function emptyArrayFactory() { return []; }
  3651. function argumentsToArray() {
  3652. var len = arguments.length, args = new Array(len);
  3653. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3654. return args;
  3655. }
  3656. var ZipIterableObservable = (function(__super__) {
  3657. inherits(ZipIterableObservable, __super__);
  3658. function ZipIterableObservable(sources, cb) {
  3659. this.sources = sources;
  3660. this._cb = cb;
  3661. __super__.call(this);
  3662. }
  3663. ZipIterableObservable.prototype.subscribeCore = function (o) {
  3664. var sources = this.sources, len = sources.length, subscriptions = new Array(len);
  3665. var state = {
  3666. q: arrayInitialize(len, emptyArrayFactory),
  3667. done: arrayInitialize(len, falseFactory),
  3668. cb: this._cb,
  3669. o: o
  3670. };
  3671. for (var i = 0; i < len; i++) {
  3672. (function (i) {
  3673. var source = sources[i], sad = new SingleAssignmentDisposable();
  3674. (isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));
  3675. subscriptions[i] = sad;
  3676. sad.setDisposable(source.subscribe(new ZipIterableObserver(state, i)));
  3677. }(i));
  3678. }
  3679. return new NAryDisposable(subscriptions);
  3680. };
  3681. return ZipIterableObservable;
  3682. }(ObservableBase));
  3683. var ZipIterableObserver = (function (__super__) {
  3684. inherits(ZipIterableObserver, __super__);
  3685. function ZipIterableObserver(s, i) {
  3686. this._s = s;
  3687. this._i = i;
  3688. __super__.call(this);
  3689. }
  3690. function notEmpty(x) { return x.length > 0; }
  3691. function shiftEach(x) { return x.shift(); }
  3692. function notTheSame(i) {
  3693. return function (x, j) {
  3694. return j !== i;
  3695. };
  3696. }
  3697. ZipIterableObserver.prototype.next = function (x) {
  3698. this._s.q[this._i].push(x);
  3699. if (this._s.q.every(notEmpty)) {
  3700. var queuedValues = this._s.q.map(shiftEach),
  3701. res = tryCatch(this._s.cb).apply(null, queuedValues);
  3702. if (res === errorObj) { return this._s.o.onError(res.e); }
  3703. this._s.o.onNext(res);
  3704. } else if (this._s.done.filter(notTheSame(this._i)).every(identity)) {
  3705. this._s.o.onCompleted();
  3706. }
  3707. };
  3708. ZipIterableObserver.prototype.error = function (e) { this._s.o.onError(e); };
  3709. ZipIterableObserver.prototype.completed = function () {
  3710. this._s.done[this._i] = true;
  3711. this._s.done.every(identity) && this._s.o.onCompleted();
  3712. };
  3713. return ZipIterableObserver;
  3714. }(AbstractObserver));
  3715. /**
  3716. * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
  3717. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
  3718. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
  3719. */
  3720. observableProto.zipIterable = function () {
  3721. if (arguments.length === 0) { throw new Error('invalid arguments'); }
  3722. var len = arguments.length, args = new Array(len);
  3723. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3724. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  3725. var parent = this;
  3726. args.unshift(parent);
  3727. return new ZipIterableObservable(args, resultSelector);
  3728. };
  3729. function asObservable(source) {
  3730. return function subscribe(o) { return source.subscribe(o); };
  3731. }
  3732. /**
  3733. * Hides the identity of an observable sequence.
  3734. * @returns {Observable} An observable sequence that hides the identity of the source sequence.
  3735. */
  3736. observableProto.asObservable = function () {
  3737. return new AnonymousObservable(asObservable(this), this);
  3738. };
  3739. function toArray(x) { return x.toArray(); }
  3740. function notEmpty(x) { return x.length > 0; }
  3741. /**
  3742. * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
  3743. * @param {Number} count Length of each buffer.
  3744. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
  3745. * @returns {Observable} An observable sequence of buffers.
  3746. */
  3747. observableProto.bufferWithCount = observableProto.bufferCount = function (count, skip) {
  3748. typeof skip !== 'number' && (skip = count);
  3749. return this.windowWithCount(count, skip)
  3750. .flatMap(toArray)
  3751. .filter(notEmpty);
  3752. };
  3753. var DematerializeObservable = (function (__super__) {
  3754. inherits(DematerializeObservable, __super__);
  3755. function DematerializeObservable(source) {
  3756. this.source = source;
  3757. __super__.call(this);
  3758. }
  3759. DematerializeObservable.prototype.subscribeCore = function (o) {
  3760. return this.source.subscribe(new DematerializeObserver(o));
  3761. };
  3762. return DematerializeObservable;
  3763. }(ObservableBase));
  3764. var DematerializeObserver = (function (__super__) {
  3765. inherits(DematerializeObserver, __super__);
  3766. function DematerializeObserver(o) {
  3767. this._o = o;
  3768. __super__.call(this);
  3769. }
  3770. DematerializeObserver.prototype.next = function (x) { x.accept(this._o); };
  3771. DematerializeObserver.prototype.error = function (e) { this._o.onError(e); };
  3772. DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); };
  3773. return DematerializeObserver;
  3774. }(AbstractObserver));
  3775. /**
  3776. * Dematerializes the explicit notification values of an observable sequence as implicit notifications.
  3777. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
  3778. */
  3779. observableProto.dematerialize = function () {
  3780. return new DematerializeObservable(this);
  3781. };
  3782. var DistinctUntilChangedObservable = (function(__super__) {
  3783. inherits(DistinctUntilChangedObservable, __super__);
  3784. function DistinctUntilChangedObservable(source, keyFn, comparer) {
  3785. this.source = source;
  3786. this.keyFn = keyFn;
  3787. this.comparer = comparer;
  3788. __super__.call(this);
  3789. }
  3790. DistinctUntilChangedObservable.prototype.subscribeCore = function (o) {
  3791. return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer));
  3792. };
  3793. return DistinctUntilChangedObservable;
  3794. }(ObservableBase));
  3795. var DistinctUntilChangedObserver = (function(__super__) {
  3796. inherits(DistinctUntilChangedObserver, __super__);
  3797. function DistinctUntilChangedObserver(o, keyFn, comparer) {
  3798. this.o = o;
  3799. this.keyFn = keyFn;
  3800. this.comparer = comparer;
  3801. this.hasCurrentKey = false;
  3802. this.currentKey = null;
  3803. __super__.call(this);
  3804. }
  3805. DistinctUntilChangedObserver.prototype.next = function (x) {
  3806. var key = x, comparerEquals;
  3807. if (isFunction(this.keyFn)) {
  3808. key = tryCatch(this.keyFn)(x);
  3809. if (key === errorObj) { return this.o.onError(key.e); }
  3810. }
  3811. if (this.hasCurrentKey) {
  3812. comparerEquals = tryCatch(this.comparer)(this.currentKey, key);
  3813. if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); }
  3814. }
  3815. if (!this.hasCurrentKey || !comparerEquals) {
  3816. this.hasCurrentKey = true;
  3817. this.currentKey = key;
  3818. this.o.onNext(x);
  3819. }
  3820. };
  3821. DistinctUntilChangedObserver.prototype.error = function(e) {
  3822. this.o.onError(e);
  3823. };
  3824. DistinctUntilChangedObserver.prototype.completed = function () {
  3825. this.o.onCompleted();
  3826. };
  3827. return DistinctUntilChangedObserver;
  3828. }(AbstractObserver));
  3829. /**
  3830. * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer.
  3831. * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value.
  3832. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
  3833. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
  3834. */
  3835. observableProto.distinctUntilChanged = function (keyFn, comparer) {
  3836. comparer || (comparer = defaultComparer);
  3837. return new DistinctUntilChangedObservable(this, keyFn, comparer);
  3838. };
  3839. var TapObservable = (function(__super__) {
  3840. inherits(TapObservable,__super__);
  3841. function TapObservable(source, observerOrOnNext, onError, onCompleted) {
  3842. this.source = source;
  3843. this._oN = observerOrOnNext;
  3844. this._oE = onError;
  3845. this._oC = onCompleted;
  3846. __super__.call(this);
  3847. }
  3848. TapObservable.prototype.subscribeCore = function(o) {
  3849. return this.source.subscribe(new InnerObserver(o, this));
  3850. };
  3851. inherits(InnerObserver, AbstractObserver);
  3852. function InnerObserver(o, p) {
  3853. this.o = o;
  3854. this.t = !p._oN || isFunction(p._oN) ?
  3855. observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) :
  3856. p._oN;
  3857. this.isStopped = false;
  3858. AbstractObserver.call(this);
  3859. }
  3860. InnerObserver.prototype.next = function(x) {
  3861. var res = tryCatch(this.t.onNext).call(this.t, x);
  3862. if (res === errorObj) { this.o.onError(res.e); }
  3863. this.o.onNext(x);
  3864. };
  3865. InnerObserver.prototype.error = function(err) {
  3866. var res = tryCatch(this.t.onError).call(this.t, err);
  3867. if (res === errorObj) { return this.o.onError(res.e); }
  3868. this.o.onError(err);
  3869. };
  3870. InnerObserver.prototype.completed = function() {
  3871. var res = tryCatch(this.t.onCompleted).call(this.t);
  3872. if (res === errorObj) { return this.o.onError(res.e); }
  3873. this.o.onCompleted();
  3874. };
  3875. return TapObservable;
  3876. }(ObservableBase));
  3877. /**
  3878. * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
  3879. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
  3880. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
  3881. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
  3882. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
  3883. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3884. */
  3885. observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
  3886. return new TapObservable(this, observerOrOnNext, onError, onCompleted);
  3887. };
  3888. /**
  3889. * Invokes an action for each element in the observable sequence.
  3890. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
  3891. * @param {Function} onNext Action to invoke for each element in the observable sequence.
  3892. * @param {Any} [thisArg] Object to use as this when executing callback.
  3893. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3894. */
  3895. observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
  3896. return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
  3897. };
  3898. /**
  3899. * Invokes an action upon exceptional termination of the observable sequence.
  3900. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
  3901. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
  3902. * @param {Any} [thisArg] Object to use as this when executing callback.
  3903. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3904. */
  3905. observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
  3906. return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
  3907. };
  3908. /**
  3909. * Invokes an action upon graceful termination of the observable sequence.
  3910. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
  3911. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
  3912. * @param {Any} [thisArg] Object to use as this when executing callback.
  3913. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3914. */
  3915. observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
  3916. return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
  3917. };
  3918. var FinallyObservable = (function (__super__) {
  3919. inherits(FinallyObservable, __super__);
  3920. function FinallyObservable(source, fn, thisArg) {
  3921. this.source = source;
  3922. this._fn = bindCallback(fn, thisArg, 0);
  3923. __super__.call(this);
  3924. }
  3925. FinallyObservable.prototype.subscribeCore = function (o) {
  3926. var d = tryCatch(this.source.subscribe).call(this.source, o);
  3927. if (d === errorObj) {
  3928. this._fn();
  3929. thrower(d.e);
  3930. }
  3931. return new FinallyDisposable(d, this._fn);
  3932. };
  3933. function FinallyDisposable(s, fn) {
  3934. this.isDisposed = false;
  3935. this._s = s;
  3936. this._fn = fn;
  3937. }
  3938. FinallyDisposable.prototype.dispose = function () {
  3939. if (!this.isDisposed) {
  3940. var res = tryCatch(this._s.dispose).call(this._s);
  3941. this._fn();
  3942. res === errorObj && thrower(res.e);
  3943. }
  3944. };
  3945. return FinallyObservable;
  3946. }(ObservableBase));
  3947. /**
  3948. * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
  3949. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
  3950. * @returns {Observable} Source sequence with the action-invoking termination behavior applied.
  3951. */
  3952. observableProto['finally'] = function (action, thisArg) {
  3953. return new FinallyObservable(this, action, thisArg);
  3954. };
  3955. var IgnoreElementsObservable = (function(__super__) {
  3956. inherits(IgnoreElementsObservable, __super__);
  3957. function IgnoreElementsObservable(source) {
  3958. this.source = source;
  3959. __super__.call(this);
  3960. }
  3961. IgnoreElementsObservable.prototype.subscribeCore = function (o) {
  3962. return this.source.subscribe(new InnerObserver(o));
  3963. };
  3964. function InnerObserver(o) {
  3965. this.o = o;
  3966. this.isStopped = false;
  3967. }
  3968. InnerObserver.prototype.onNext = noop;
  3969. InnerObserver.prototype.onError = function (err) {
  3970. if(!this.isStopped) {
  3971. this.isStopped = true;
  3972. this.o.onError(err);
  3973. }
  3974. };
  3975. InnerObserver.prototype.onCompleted = function () {
  3976. if(!this.isStopped) {
  3977. this.isStopped = true;
  3978. this.o.onCompleted();
  3979. }
  3980. };
  3981. InnerObserver.prototype.dispose = function() { this.isStopped = true; };
  3982. InnerObserver.prototype.fail = function (e) {
  3983. if (!this.isStopped) {
  3984. this.isStopped = true;
  3985. this.observer.onError(e);
  3986. return true;
  3987. }
  3988. return false;
  3989. };
  3990. return IgnoreElementsObservable;
  3991. }(ObservableBase));
  3992. /**
  3993. * Ignores all elements in an observable sequence leaving only the termination messages.
  3994. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
  3995. */
  3996. observableProto.ignoreElements = function () {
  3997. return new IgnoreElementsObservable(this);
  3998. };
  3999. var MaterializeObservable = (function (__super__) {
  4000. inherits(MaterializeObservable, __super__);
  4001. function MaterializeObservable(source, fn) {
  4002. this.source = source;
  4003. __super__.call(this);
  4004. }
  4005. MaterializeObservable.prototype.subscribeCore = function (o) {
  4006. return this.source.subscribe(new MaterializeObserver(o));
  4007. };
  4008. return MaterializeObservable;
  4009. }(ObservableBase));
  4010. var MaterializeObserver = (function (__super__) {
  4011. inherits(MaterializeObserver, __super__);
  4012. function MaterializeObserver(o) {
  4013. this._o = o;
  4014. __super__.call(this);
  4015. }
  4016. MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) };
  4017. MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); };
  4018. MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); };
  4019. return MaterializeObserver;
  4020. }(AbstractObserver));
  4021. /**
  4022. * Materializes the implicit notifications of an observable sequence as explicit notification values.
  4023. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
  4024. */
  4025. observableProto.materialize = function () {
  4026. return new MaterializeObservable(this);
  4027. };
  4028. /**
  4029. * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
  4030. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
  4031. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
  4032. */
  4033. observableProto.repeat = function (repeatCount) {
  4034. return enumerableRepeat(this, repeatCount).concat();
  4035. };
  4036. /**
  4037. * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
  4038. * Note if you encounter an error and want it to retry once, then you must use .retry(2);
  4039. *
  4040. * @example
  4041. * var res = retried = retry.repeat();
  4042. * var res = retried = retry.repeat(2);
  4043. * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
  4044. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
  4045. */
  4046. observableProto.retry = function (retryCount) {
  4047. return enumerableRepeat(this, retryCount).catchError();
  4048. };
  4049. function repeat(value) {
  4050. return {
  4051. '@@iterator': function () {
  4052. return {
  4053. next: function () {
  4054. return { done: false, value: value };
  4055. }
  4056. };
  4057. }
  4058. };
  4059. }
  4060. var RetryWhenObservable = (function(__super__) {
  4061. function createDisposable(state) {
  4062. return {
  4063. isDisposed: false,
  4064. dispose: function () {
  4065. if (!this.isDisposed) {
  4066. this.isDisposed = true;
  4067. state.isDisposed = true;
  4068. }
  4069. }
  4070. };
  4071. }
  4072. function RetryWhenObservable(source, notifier) {
  4073. this.source = source;
  4074. this._notifier = notifier;
  4075. __super__.call(this);
  4076. }
  4077. inherits(RetryWhenObservable, __super__);
  4078. RetryWhenObservable.prototype.subscribeCore = function (o) {
  4079. var exceptions = new Subject(),
  4080. notifier = new Subject(),
  4081. handled = this._notifier(exceptions),
  4082. notificationDisposable = handled.subscribe(notifier);
  4083. var e = this.source['@@iterator']();
  4084. var state = { isDisposed: false },
  4085. lastError,
  4086. subscription = new SerialDisposable();
  4087. var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) {
  4088. if (state.isDisposed) { return; }
  4089. var currentItem = e.next();
  4090. if (currentItem.done) {
  4091. if (lastError) {
  4092. o.onError(lastError);
  4093. } else {
  4094. o.onCompleted();
  4095. }
  4096. return;
  4097. }
  4098. // Check if promise
  4099. var currentValue = currentItem.value;
  4100. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  4101. var outer = new SingleAssignmentDisposable();
  4102. var inner = new SingleAssignmentDisposable();
  4103. subscription.setDisposable(new BinaryDisposable(inner, outer));
  4104. outer.setDisposable(currentValue.subscribe(
  4105. function(x) { o.onNext(x); },
  4106. function (exn) {
  4107. inner.setDisposable(notifier.subscribe(recurse, function(ex) {
  4108. o.onError(ex);
  4109. }, function() {
  4110. o.onCompleted();
  4111. }));
  4112. exceptions.onNext(exn);
  4113. outer.dispose();
  4114. },
  4115. function() { o.onCompleted(); }));
  4116. });
  4117. return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]);
  4118. };
  4119. return RetryWhenObservable;
  4120. }(ObservableBase));
  4121. observableProto.retryWhen = function (notifier) {
  4122. return new RetryWhenObservable(repeat(this), notifier);
  4123. };
  4124. function repeat(value) {
  4125. return {
  4126. '@@iterator': function () {
  4127. return {
  4128. next: function () {
  4129. return { done: false, value: value };
  4130. }
  4131. };
  4132. }
  4133. };
  4134. }
  4135. var RepeatWhenObservable = (function(__super__) {
  4136. function createDisposable(state) {
  4137. return {
  4138. isDisposed: false,
  4139. dispose: function () {
  4140. if (!this.isDisposed) {
  4141. this.isDisposed = true;
  4142. state.isDisposed = true;
  4143. }
  4144. }
  4145. };
  4146. }
  4147. function RepeatWhenObservable(source, notifier) {
  4148. this.source = source;
  4149. this._notifier = notifier;
  4150. __super__.call(this);
  4151. }
  4152. inherits(RepeatWhenObservable, __super__);
  4153. RepeatWhenObservable.prototype.subscribeCore = function (o) {
  4154. var completions = new Subject(),
  4155. notifier = new Subject(),
  4156. handled = this._notifier(completions),
  4157. notificationDisposable = handled.subscribe(notifier);
  4158. var e = this.source['@@iterator']();
  4159. var state = { isDisposed: false },
  4160. lastError,
  4161. subscription = new SerialDisposable();
  4162. var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) {
  4163. if (state.isDisposed) { return; }
  4164. var currentItem = e.next();
  4165. if (currentItem.done) {
  4166. if (lastError) {
  4167. o.onError(lastError);
  4168. } else {
  4169. o.onCompleted();
  4170. }
  4171. return;
  4172. }
  4173. // Check if promise
  4174. var currentValue = currentItem.value;
  4175. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  4176. var outer = new SingleAssignmentDisposable();
  4177. var inner = new SingleAssignmentDisposable();
  4178. subscription.setDisposable(new BinaryDisposable(inner, outer));
  4179. outer.setDisposable(currentValue.subscribe(
  4180. function(x) { o.onNext(x); },
  4181. function (exn) { o.onError(exn); },
  4182. function() {
  4183. inner.setDisposable(notifier.subscribe(recurse, function(ex) {
  4184. o.onError(ex);
  4185. }, function() {
  4186. o.onCompleted();
  4187. }));
  4188. completions.onNext(null);
  4189. outer.dispose();
  4190. }));
  4191. });
  4192. return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]);
  4193. };
  4194. return RepeatWhenObservable;
  4195. }(ObservableBase));
  4196. observableProto.repeatWhen = function (notifier) {
  4197. return new RepeatWhenObservable(repeat(this), notifier);
  4198. };
  4199. var ScanObservable = (function(__super__) {
  4200. inherits(ScanObservable, __super__);
  4201. function ScanObservable(source, accumulator, hasSeed, seed) {
  4202. this.source = source;
  4203. this.accumulator = accumulator;
  4204. this.hasSeed = hasSeed;
  4205. this.seed = seed;
  4206. __super__.call(this);
  4207. }
  4208. ScanObservable.prototype.subscribeCore = function(o) {
  4209. return this.source.subscribe(new ScanObserver(o,this));
  4210. };
  4211. return ScanObservable;
  4212. }(ObservableBase));
  4213. var ScanObserver = (function (__super__) {
  4214. inherits(ScanObserver, __super__);
  4215. function ScanObserver(o, parent) {
  4216. this._o = o;
  4217. this._p = parent;
  4218. this._fn = parent.accumulator;
  4219. this._hs = parent.hasSeed;
  4220. this._s = parent.seed;
  4221. this._ha = false;
  4222. this._a = null;
  4223. this._hv = false;
  4224. this._i = 0;
  4225. __super__.call(this);
  4226. }
  4227. ScanObserver.prototype.next = function (x) {
  4228. !this._hv && (this._hv = true);
  4229. if (this._ha) {
  4230. this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
  4231. } else {
  4232. this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
  4233. this._ha = true;
  4234. }
  4235. if (this._a === errorObj) { return this._o.onError(this._a.e); }
  4236. this._o.onNext(this._a);
  4237. this._i++;
  4238. };
  4239. ScanObserver.prototype.error = function (e) {
  4240. this._o.onError(e);
  4241. };
  4242. ScanObserver.prototype.completed = function () {
  4243. !this._hv && this._hs && this._o.onNext(this._s);
  4244. this._o.onCompleted();
  4245. };
  4246. return ScanObserver;
  4247. }(AbstractObserver));
  4248. /**
  4249. * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
  4250. * For aggregation behavior with no intermediate results, see Observable.aggregate.
  4251. * @param {Mixed} [seed] The initial accumulator value.
  4252. * @param {Function} accumulator An accumulator function to be invoked on each element.
  4253. * @returns {Observable} An observable sequence containing the accumulated values.
  4254. */
  4255. observableProto.scan = function () {
  4256. var hasSeed = false, seed, accumulator = arguments[0];
  4257. if (arguments.length === 2) {
  4258. hasSeed = true;
  4259. seed = arguments[1];
  4260. }
  4261. return new ScanObservable(this, accumulator, hasSeed, seed);
  4262. };
  4263. var SkipLastObservable = (function (__super__) {
  4264. inherits(SkipLastObservable, __super__);
  4265. function SkipLastObservable(source, c) {
  4266. this.source = source;
  4267. this._c = c;
  4268. __super__.call(this);
  4269. }
  4270. SkipLastObservable.prototype.subscribeCore = function (o) {
  4271. return this.source.subscribe(new SkipLastObserver(o, this._c));
  4272. };
  4273. return SkipLastObservable;
  4274. }(ObservableBase));
  4275. var SkipLastObserver = (function (__super__) {
  4276. inherits(SkipLastObserver, __super__);
  4277. function SkipLastObserver(o, c) {
  4278. this._o = o;
  4279. this._c = c;
  4280. this._q = [];
  4281. __super__.call(this);
  4282. }
  4283. SkipLastObserver.prototype.next = function (x) {
  4284. this._q.push(x);
  4285. this._q.length > this._c && this._o.onNext(this._q.shift());
  4286. };
  4287. SkipLastObserver.prototype.error = function (e) {
  4288. this._o.onError(e);
  4289. };
  4290. SkipLastObserver.prototype.completed = function () {
  4291. this._o.onCompleted();
  4292. };
  4293. return SkipLastObserver;
  4294. }(AbstractObserver));
  4295. /**
  4296. * Bypasses a specified number of elements at the end of an observable sequence.
  4297. * @description
  4298. * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
  4299. * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
  4300. * @param count Number of elements to bypass at the end of the source sequence.
  4301. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
  4302. */
  4303. observableProto.skipLast = function (count) {
  4304. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  4305. return new SkipLastObservable(this, count);
  4306. };
  4307. /**
  4308. * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
  4309. * @example
  4310. * var res = source.startWith(1, 2, 3);
  4311. * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
  4312. * @param {Arguments} args The specified values to prepend to the observable sequence
  4313. * @returns {Observable} The source sequence prepended with the specified values.
  4314. */
  4315. observableProto.startWith = function () {
  4316. var values, scheduler, start = 0;
  4317. if (!!arguments.length && isScheduler(arguments[0])) {
  4318. scheduler = arguments[0];
  4319. start = 1;
  4320. } else {
  4321. scheduler = immediateScheduler;
  4322. }
  4323. for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
  4324. return observableConcat.apply(null, [observableFromArray(args, scheduler), this]);
  4325. };
  4326. var TakeLastObserver = (function (__super__) {
  4327. inherits(TakeLastObserver, __super__);
  4328. function TakeLastObserver(o, c) {
  4329. this._o = o;
  4330. this._c = c;
  4331. this._q = [];
  4332. __super__.call(this);
  4333. }
  4334. TakeLastObserver.prototype.next = function (x) {
  4335. this._q.push(x);
  4336. this._q.length > this._c && this._q.shift();
  4337. };
  4338. TakeLastObserver.prototype.error = function (e) {
  4339. this._o.onError(e);
  4340. };
  4341. TakeLastObserver.prototype.completed = function () {
  4342. while (this._q.length > 0) { this._o.onNext(this._q.shift()); }
  4343. this._o.onCompleted();
  4344. };
  4345. return TakeLastObserver;
  4346. }(AbstractObserver));
  4347. /**
  4348. * Returns a specified number of contiguous elements from the end of an observable sequence.
  4349. * @description
  4350. * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
  4351. * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
  4352. * @param {Number} count Number of elements to take from the end of the source sequence.
  4353. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
  4354. */
  4355. observableProto.takeLast = function (count) {
  4356. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  4357. var source = this;
  4358. return new AnonymousObservable(function (o) {
  4359. return source.subscribe(new TakeLastObserver(o, count));
  4360. }, source);
  4361. };
  4362. var TakeLastBufferObserver = (function (__super__) {
  4363. inherits(TakeLastBufferObserver, __super__);
  4364. function TakeLastBufferObserver(o, c) {
  4365. this._o = o;
  4366. this._c = c;
  4367. this._q = [];
  4368. __super__.call(this);
  4369. }
  4370. TakeLastBufferObserver.prototype.next = function (x) {
  4371. this._q.push(x);
  4372. this._q.length > this._c && this._q.shift();
  4373. };
  4374. TakeLastBufferObserver.prototype.error = function (e) {
  4375. this._o.onError(e);
  4376. };
  4377. TakeLastBufferObserver.prototype.completed = function () {
  4378. this._o.onNext(this._q);
  4379. this._o.onCompleted();
  4380. };
  4381. return TakeLastBufferObserver;
  4382. }(AbstractObserver));
  4383. /**
  4384. * Returns an array with the specified number of contiguous elements from the end of an observable sequence.
  4385. *
  4386. * @description
  4387. * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
  4388. * source sequence, this buffer is produced on the result sequence.
  4389. * @param {Number} count Number of elements to take from the end of the source sequence.
  4390. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
  4391. */
  4392. observableProto.takeLastBuffer = function (count) {
  4393. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  4394. var source = this;
  4395. return new AnonymousObservable(function (o) {
  4396. return source.subscribe(new TakeLastBufferObserver(o, count));
  4397. }, source);
  4398. };
  4399. /**
  4400. * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
  4401. * @param {Number} count Length of each window.
  4402. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
  4403. * @returns {Observable} An observable sequence of windows.
  4404. */
  4405. observableProto.windowWithCount = observableProto.windowCount = function (count, skip) {
  4406. var source = this;
  4407. +count || (count = 0);
  4408. Math.abs(count) === Infinity && (count = 0);
  4409. if (count <= 0) { throw new ArgumentOutOfRangeError(); }
  4410. skip == null && (skip = count);
  4411. +skip || (skip = 0);
  4412. Math.abs(skip) === Infinity && (skip = 0);
  4413. if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
  4414. return new AnonymousObservable(function (observer) {
  4415. var m = new SingleAssignmentDisposable(),
  4416. refCountDisposable = new RefCountDisposable(m),
  4417. n = 0,
  4418. q = [];
  4419. function createWindow () {
  4420. var s = new Subject();
  4421. q.push(s);
  4422. observer.onNext(addRef(s, refCountDisposable));
  4423. }
  4424. createWindow();
  4425. m.setDisposable(source.subscribe(
  4426. function (x) {
  4427. for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
  4428. var c = n - count + 1;
  4429. c >= 0 && c % skip === 0 && q.shift().onCompleted();
  4430. ++n % skip === 0 && createWindow();
  4431. },
  4432. function (e) {
  4433. while (q.length > 0) { q.shift().onError(e); }
  4434. observer.onError(e);
  4435. },
  4436. function () {
  4437. while (q.length > 0) { q.shift().onCompleted(); }
  4438. observer.onCompleted();
  4439. }
  4440. ));
  4441. return refCountDisposable;
  4442. }, source);
  4443. };
  4444. function concatMap(source, selector, thisArg) {
  4445. var selectorFunc = bindCallback(selector, thisArg, 3);
  4446. return source.map(function (x, i) {
  4447. var result = selectorFunc(x, i, source);
  4448. isPromise(result) && (result = observableFromPromise(result));
  4449. (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
  4450. return result;
  4451. }).concatAll();
  4452. }
  4453. /**
  4454. * One of the Following:
  4455. * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
  4456. *
  4457. * @example
  4458. * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
  4459. * Or:
  4460. * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
  4461. *
  4462. * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
  4463. * Or:
  4464. * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
  4465. *
  4466. * var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
  4467. * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
  4468. * source sequence onto which could be either an observable or Promise.
  4469. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
  4470. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
  4471. */
  4472. observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
  4473. if (isFunction(selector) && isFunction(resultSelector)) {
  4474. return this.concatMap(function (x, i) {
  4475. var selectorResult = selector(x, i);
  4476. isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
  4477. (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
  4478. return selectorResult.map(function (y, i2) {
  4479. return resultSelector(x, y, i, i2);
  4480. });
  4481. });
  4482. }
  4483. return isFunction(selector) ?
  4484. concatMap(this, selector, thisArg) :
  4485. concatMap(this, function () { return selector; });
  4486. };
  4487. /**
  4488. * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
  4489. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
  4490. * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
  4491. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
  4492. * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
  4493. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
  4494. */
  4495. observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
  4496. var source = this,
  4497. onNextFunc = bindCallback(onNext, thisArg, 2),
  4498. onErrorFunc = bindCallback(onError, thisArg, 1),
  4499. onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
  4500. return new AnonymousObservable(function (observer) {
  4501. var index = 0;
  4502. return source.subscribe(
  4503. function (x) {
  4504. var result;
  4505. try {
  4506. result = onNextFunc(x, index++);
  4507. } catch (e) {
  4508. observer.onError(e);
  4509. return;
  4510. }
  4511. isPromise(result) && (result = observableFromPromise(result));
  4512. observer.onNext(result);
  4513. },
  4514. function (err) {
  4515. var result;
  4516. try {
  4517. result = onErrorFunc(err);
  4518. } catch (e) {
  4519. observer.onError(e);
  4520. return;
  4521. }
  4522. isPromise(result) && (result = observableFromPromise(result));
  4523. observer.onNext(result);
  4524. observer.onCompleted();
  4525. },
  4526. function () {
  4527. var result;
  4528. try {
  4529. result = onCompletedFunc();
  4530. } catch (e) {
  4531. observer.onError(e);
  4532. return;
  4533. }
  4534. isPromise(result) && (result = observableFromPromise(result));
  4535. observer.onNext(result);
  4536. observer.onCompleted();
  4537. });
  4538. }, this).concatAll();
  4539. };
  4540. var DefaultIfEmptyObserver = (function (__super__) {
  4541. inherits(DefaultIfEmptyObserver, __super__);
  4542. function DefaultIfEmptyObserver(o, d) {
  4543. this._o = o;
  4544. this._d = d;
  4545. this._f = false;
  4546. __super__.call(this);
  4547. }
  4548. DefaultIfEmptyObserver.prototype.next = function (x) {
  4549. this._f = true;
  4550. this._o.onNext(x);
  4551. };
  4552. DefaultIfEmptyObserver.prototype.error = function (e) {
  4553. this._o.onError(e);
  4554. };
  4555. DefaultIfEmptyObserver.prototype.completed = function () {
  4556. !this._f && this._o.onNext(this._d);
  4557. this._o.onCompleted();
  4558. };
  4559. return DefaultIfEmptyObserver;
  4560. }(AbstractObserver));
  4561. /**
  4562. * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
  4563. *
  4564. * var res = obs = xs.defaultIfEmpty();
  4565. * 2 - obs = xs.defaultIfEmpty(false);
  4566. *
  4567. * @memberOf Observable#
  4568. * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
  4569. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
  4570. */
  4571. observableProto.defaultIfEmpty = function (defaultValue) {
  4572. var source = this;
  4573. defaultValue === undefined && (defaultValue = null);
  4574. return new AnonymousObservable(function (o) {
  4575. return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue));
  4576. }, source);
  4577. };
  4578. // Swap out for Array.findIndex
  4579. function arrayIndexOfComparer(array, item, comparer) {
  4580. for (var i = 0, len = array.length; i < len; i++) {
  4581. if (comparer(array[i], item)) { return i; }
  4582. }
  4583. return -1;
  4584. }
  4585. function HashSet(comparer) {
  4586. this.comparer = comparer;
  4587. this.set = [];
  4588. }
  4589. HashSet.prototype.push = function(value) {
  4590. var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
  4591. retValue && this.set.push(value);
  4592. return retValue;
  4593. };
  4594. var DistinctObservable = (function (__super__) {
  4595. inherits(DistinctObservable, __super__);
  4596. function DistinctObservable(source, keyFn, cmpFn) {
  4597. this.source = source;
  4598. this._keyFn = keyFn;
  4599. this._cmpFn = cmpFn;
  4600. __super__.call(this);
  4601. }
  4602. DistinctObservable.prototype.subscribeCore = function (o) {
  4603. return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn));
  4604. };
  4605. return DistinctObservable;
  4606. }(ObservableBase));
  4607. var DistinctObserver = (function (__super__) {
  4608. inherits(DistinctObserver, __super__);
  4609. function DistinctObserver(o, keyFn, cmpFn) {
  4610. this._o = o;
  4611. this._keyFn = keyFn;
  4612. this._h = new HashSet(cmpFn);
  4613. __super__.call(this);
  4614. }
  4615. DistinctObserver.prototype.next = function (x) {
  4616. var key = x;
  4617. if (isFunction(this._keyFn)) {
  4618. key = tryCatch(this._keyFn)(x);
  4619. if (key === errorObj) { return this._o.onError(key.e); }
  4620. }
  4621. this._h.push(key) && this._o.onNext(x);
  4622. };
  4623. DistinctObserver.prototype.error = function (e) { this._o.onError(e); };
  4624. DistinctObserver.prototype.completed = function () { this._o.onCompleted(); };
  4625. return DistinctObserver;
  4626. }(AbstractObserver));
  4627. /**
  4628. * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
  4629. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
  4630. *
  4631. * @example
  4632. * var res = obs = xs.distinct();
  4633. * 2 - obs = xs.distinct(function (x) { return x.id; });
  4634. * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
  4635. * @param {Function} [keySelector] A function to compute the comparison key for each element.
  4636. * @param {Function} [comparer] Used to compare items in the collection.
  4637. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
  4638. */
  4639. observableProto.distinct = function (keySelector, comparer) {
  4640. comparer || (comparer = defaultComparer);
  4641. return new DistinctObservable(this, keySelector, comparer);
  4642. };
  4643. /**
  4644. * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
  4645. *
  4646. * @example
  4647. * var res = observable.groupBy(function (x) { return x.id; });
  4648. * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
  4649. * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
  4650. * @param {Function} keySelector A function to extract the key for each element.
  4651. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
  4652. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
  4653. */
  4654. observableProto.groupBy = function (keySelector, elementSelector) {
  4655. return this.groupByUntil(keySelector, elementSelector, observableNever);
  4656. };
  4657. /**
  4658. * Groups the elements of an observable sequence according to a specified key selector function.
  4659. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
  4660. * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
  4661. *
  4662. * @example
  4663. * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
  4664. * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
  4665. * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
  4666. * @param {Function} keySelector A function to extract the key for each element.
  4667. * @param {Function} durationSelector A function to signal the expiration of a group.
  4668. * @returns {Observable}
  4669. * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
  4670. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
  4671. *
  4672. */
  4673. observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector) {
  4674. var source = this;
  4675. return new AnonymousObservable(function (o) {
  4676. var map = new Map(),
  4677. groupDisposable = new CompositeDisposable(),
  4678. refCountDisposable = new RefCountDisposable(groupDisposable),
  4679. handleError = function (e) { return function (item) { item.onError(e); }; };
  4680. groupDisposable.add(
  4681. source.subscribe(function (x) {
  4682. var key = tryCatch(keySelector)(x);
  4683. if (key === errorObj) {
  4684. map.forEach(handleError(key.e));
  4685. return o.onError(key.e);
  4686. }
  4687. var fireNewMapEntry = false, writer = map.get(key);
  4688. if (writer === undefined) {
  4689. writer = new Subject();
  4690. map.set(key, writer);
  4691. fireNewMapEntry = true;
  4692. }
  4693. if (fireNewMapEntry) {
  4694. var group = new GroupedObservable(key, writer, refCountDisposable),
  4695. durationGroup = new GroupedObservable(key, writer);
  4696. var duration = tryCatch(durationSelector)(durationGroup);
  4697. if (duration === errorObj) {
  4698. map.forEach(handleError(duration.e));
  4699. return o.onError(duration.e);
  4700. }
  4701. o.onNext(group);
  4702. var md = new SingleAssignmentDisposable();
  4703. groupDisposable.add(md);
  4704. md.setDisposable(duration.take(1).subscribe(
  4705. noop,
  4706. function (e) {
  4707. map.forEach(handleError(e));
  4708. o.onError(e);
  4709. },
  4710. function () {
  4711. if (map['delete'](key)) { writer.onCompleted(); }
  4712. groupDisposable.remove(md);
  4713. }));
  4714. }
  4715. var element = x;
  4716. if (isFunction(elementSelector)) {
  4717. element = tryCatch(elementSelector)(x);
  4718. if (element === errorObj) {
  4719. map.forEach(handleError(element.e));
  4720. return o.onError(element.e);
  4721. }
  4722. }
  4723. writer.onNext(element);
  4724. }, function (e) {
  4725. map.forEach(handleError(e));
  4726. o.onError(e);
  4727. }, function () {
  4728. map.forEach(function (item) { item.onCompleted(); });
  4729. o.onCompleted();
  4730. }));
  4731. return refCountDisposable;
  4732. }, source);
  4733. };
  4734. var MapObservable = (function (__super__) {
  4735. inherits(MapObservable, __super__);
  4736. function MapObservable(source, selector, thisArg) {
  4737. this.source = source;
  4738. this.selector = bindCallback(selector, thisArg, 3);
  4739. __super__.call(this);
  4740. }
  4741. function innerMap(selector, self) {
  4742. return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); };
  4743. }
  4744. MapObservable.prototype.internalMap = function (selector, thisArg) {
  4745. return new MapObservable(this.source, innerMap(selector, this), thisArg);
  4746. };
  4747. MapObservable.prototype.subscribeCore = function (o) {
  4748. return this.source.subscribe(new InnerObserver(o, this.selector, this));
  4749. };
  4750. inherits(InnerObserver, AbstractObserver);
  4751. function InnerObserver(o, selector, source) {
  4752. this.o = o;
  4753. this.selector = selector;
  4754. this.source = source;
  4755. this.i = 0;
  4756. AbstractObserver.call(this);
  4757. }
  4758. InnerObserver.prototype.next = function(x) {
  4759. var result = tryCatch(this.selector)(x, this.i++, this.source);
  4760. if (result === errorObj) { return this.o.onError(result.e); }
  4761. this.o.onNext(result);
  4762. };
  4763. InnerObserver.prototype.error = function (e) {
  4764. this.o.onError(e);
  4765. };
  4766. InnerObserver.prototype.completed = function () {
  4767. this.o.onCompleted();
  4768. };
  4769. return MapObservable;
  4770. }(ObservableBase));
  4771. /**
  4772. * Projects each element of an observable sequence into a new form by incorporating the element's index.
  4773. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
  4774. * @param {Any} [thisArg] Object to use as this when executing callback.
  4775. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
  4776. */
  4777. observableProto.map = observableProto.select = function (selector, thisArg) {
  4778. var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
  4779. return this instanceof MapObservable ?
  4780. this.internalMap(selectorFn, thisArg) :
  4781. new MapObservable(this, selectorFn, thisArg);
  4782. };
  4783. function plucker(args, len) {
  4784. return function mapper(x) {
  4785. var currentProp = x;
  4786. for (var i = 0; i < len; i++) {
  4787. var p = currentProp[args[i]];
  4788. if (typeof p !== 'undefined') {
  4789. currentProp = p;
  4790. } else {
  4791. return undefined;
  4792. }
  4793. }
  4794. return currentProp;
  4795. };
  4796. }
  4797. /**
  4798. * Retrieves the value of a specified nested property from all elements in
  4799. * the Observable sequence.
  4800. * @param {Arguments} arguments The nested properties to pluck.
  4801. * @returns {Observable} Returns a new Observable sequence of property values.
  4802. */
  4803. observableProto.pluck = function () {
  4804. var len = arguments.length, args = new Array(len);
  4805. if (len === 0) { throw new Error('List of properties cannot be empty.'); }
  4806. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  4807. return this.map(plucker(args, len));
  4808. };
  4809. observableProto.flatMap = observableProto.selectMany = observableProto.mergeMap = function(selector, resultSelector, thisArg) {
  4810. return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll();
  4811. };
  4812. /**
  4813. * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
  4814. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
  4815. * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
  4816. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
  4817. * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
  4818. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
  4819. */
  4820. observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
  4821. var source = this;
  4822. return new AnonymousObservable(function (observer) {
  4823. var index = 0;
  4824. return source.subscribe(
  4825. function (x) {
  4826. var result;
  4827. try {
  4828. result = onNext.call(thisArg, x, index++);
  4829. } catch (e) {
  4830. observer.onError(e);
  4831. return;
  4832. }
  4833. isPromise(result) && (result = observableFromPromise(result));
  4834. observer.onNext(result);
  4835. },
  4836. function (err) {
  4837. var result;
  4838. try {
  4839. result = onError.call(thisArg, err);
  4840. } catch (e) {
  4841. observer.onError(e);
  4842. return;
  4843. }
  4844. isPromise(result) && (result = observableFromPromise(result));
  4845. observer.onNext(result);
  4846. observer.onCompleted();
  4847. },
  4848. function () {
  4849. var result;
  4850. try {
  4851. result = onCompleted.call(thisArg);
  4852. } catch (e) {
  4853. observer.onError(e);
  4854. return;
  4855. }
  4856. isPromise(result) && (result = observableFromPromise(result));
  4857. observer.onNext(result);
  4858. observer.onCompleted();
  4859. });
  4860. }, source).mergeAll();
  4861. };
  4862. observableProto.flatMapLatest = observableProto.switchMap = function(selector, resultSelector, thisArg) {
  4863. return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest();
  4864. };
  4865. var SkipObservable = (function(__super__) {
  4866. inherits(SkipObservable, __super__);
  4867. function SkipObservable(source, count) {
  4868. this.source = source;
  4869. this._count = count;
  4870. __super__.call(this);
  4871. }
  4872. SkipObservable.prototype.subscribeCore = function (o) {
  4873. return this.source.subscribe(new SkipObserver(o, this._count));
  4874. };
  4875. function SkipObserver(o, c) {
  4876. this._o = o;
  4877. this._r = c;
  4878. AbstractObserver.call(this);
  4879. }
  4880. inherits(SkipObserver, AbstractObserver);
  4881. SkipObserver.prototype.next = function (x) {
  4882. if (this._r <= 0) {
  4883. this._o.onNext(x);
  4884. } else {
  4885. this._r--;
  4886. }
  4887. };
  4888. SkipObserver.prototype.error = function(e) { this._o.onError(e); };
  4889. SkipObserver.prototype.completed = function() { this._o.onCompleted(); };
  4890. return SkipObservable;
  4891. }(ObservableBase));
  4892. /**
  4893. * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
  4894. * @param {Number} count The number of elements to skip before returning the remaining elements.
  4895. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
  4896. */
  4897. observableProto.skip = function (count) {
  4898. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  4899. return new SkipObservable(this, count);
  4900. };
  4901. var SkipWhileObservable = (function (__super__) {
  4902. inherits(SkipWhileObservable, __super__);
  4903. function SkipWhileObservable(source, fn) {
  4904. this.source = source;
  4905. this._fn = fn;
  4906. __super__.call(this);
  4907. }
  4908. SkipWhileObservable.prototype.subscribeCore = function (o) {
  4909. return this.source.subscribe(new SkipWhileObserver(o, this));
  4910. };
  4911. return SkipWhileObservable;
  4912. }(ObservableBase));
  4913. var SkipWhileObserver = (function (__super__) {
  4914. inherits(SkipWhileObserver, __super__);
  4915. function SkipWhileObserver(o, p) {
  4916. this._o = o;
  4917. this._p = p;
  4918. this._i = 0;
  4919. this._r = false;
  4920. __super__.call(this);
  4921. }
  4922. SkipWhileObserver.prototype.next = function (x) {
  4923. if (!this._r) {
  4924. var res = tryCatch(this._p._fn)(x, this._i++, this._p);
  4925. if (res === errorObj) { return this._o.onError(res.e); }
  4926. this._r = !res;
  4927. }
  4928. this._r && this._o.onNext(x);
  4929. };
  4930. SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); };
  4931. SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
  4932. return SkipWhileObserver;
  4933. }(AbstractObserver));
  4934. /**
  4935. * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
  4936. * The element's index is used in the logic of the predicate function.
  4937. *
  4938. * var res = source.skipWhile(function (value) { return value < 10; });
  4939. * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
  4940. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
  4941. * @param {Any} [thisArg] Object to use as this when executing callback.
  4942. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
  4943. */
  4944. observableProto.skipWhile = function (predicate, thisArg) {
  4945. var fn = bindCallback(predicate, thisArg, 3);
  4946. return new SkipWhileObservable(this, fn);
  4947. };
  4948. var TakeObservable = (function(__super__) {
  4949. inherits(TakeObservable, __super__);
  4950. function TakeObservable(source, count) {
  4951. this.source = source;
  4952. this._count = count;
  4953. __super__.call(this);
  4954. }
  4955. TakeObservable.prototype.subscribeCore = function (o) {
  4956. return this.source.subscribe(new TakeObserver(o, this._count));
  4957. };
  4958. function TakeObserver(o, c) {
  4959. this._o = o;
  4960. this._c = c;
  4961. this._r = c;
  4962. AbstractObserver.call(this);
  4963. }
  4964. inherits(TakeObserver, AbstractObserver);
  4965. TakeObserver.prototype.next = function (x) {
  4966. if (this._r-- > 0) {
  4967. this._o.onNext(x);
  4968. this._r <= 0 && this._o.onCompleted();
  4969. }
  4970. };
  4971. TakeObserver.prototype.error = function (e) { this._o.onError(e); };
  4972. TakeObserver.prototype.completed = function () { this._o.onCompleted(); };
  4973. return TakeObservable;
  4974. }(ObservableBase));
  4975. /**
  4976. * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
  4977. * @param {Number} count The number of elements to return.
  4978. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
  4979. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
  4980. */
  4981. observableProto.take = function (count, scheduler) {
  4982. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  4983. if (count === 0) { return observableEmpty(scheduler); }
  4984. return new TakeObservable(this, count);
  4985. };
  4986. var TakeWhileObservable = (function (__super__) {
  4987. inherits(TakeWhileObservable, __super__);
  4988. function TakeWhileObservable(source, fn) {
  4989. this.source = source;
  4990. this._fn = fn;
  4991. __super__.call(this);
  4992. }
  4993. TakeWhileObservable.prototype.subscribeCore = function (o) {
  4994. return this.source.subscribe(new TakeWhileObserver(o, this));
  4995. };
  4996. return TakeWhileObservable;
  4997. }(ObservableBase));
  4998. var TakeWhileObserver = (function (__super__) {
  4999. inherits(TakeWhileObserver, __super__);
  5000. function TakeWhileObserver(o, p) {
  5001. this._o = o;
  5002. this._p = p;
  5003. this._i = 0;
  5004. this._r = true;
  5005. __super__.call(this);
  5006. }
  5007. TakeWhileObserver.prototype.next = function (x) {
  5008. if (this._r) {
  5009. this._r = tryCatch(this._p._fn)(x, this._i++, this._p);
  5010. if (this._r === errorObj) { return this._o.onError(this._r.e); }
  5011. }
  5012. if (this._r) {
  5013. this._o.onNext(x);
  5014. } else {
  5015. this._o.onCompleted();
  5016. }
  5017. };
  5018. TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); };
  5019. TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
  5020. return TakeWhileObserver;
  5021. }(AbstractObserver));
  5022. /**
  5023. * Returns elements from an observable sequence as long as a specified condition is true.
  5024. * The element's index is used in the logic of the predicate function.
  5025. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
  5026. * @param {Any} [thisArg] Object to use as this when executing callback.
  5027. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
  5028. */
  5029. observableProto.takeWhile = function (predicate, thisArg) {
  5030. var fn = bindCallback(predicate, thisArg, 3);
  5031. return new TakeWhileObservable(this, fn);
  5032. };
  5033. var FilterObservable = (function (__super__) {
  5034. inherits(FilterObservable, __super__);
  5035. function FilterObservable(source, predicate, thisArg) {
  5036. this.source = source;
  5037. this.predicate = bindCallback(predicate, thisArg, 3);
  5038. __super__.call(this);
  5039. }
  5040. FilterObservable.prototype.subscribeCore = function (o) {
  5041. return this.source.subscribe(new InnerObserver(o, this.predicate, this));
  5042. };
  5043. function innerPredicate(predicate, self) {
  5044. return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
  5045. }
  5046. FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
  5047. return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
  5048. };
  5049. inherits(InnerObserver, AbstractObserver);
  5050. function InnerObserver(o, predicate, source) {
  5051. this.o = o;
  5052. this.predicate = predicate;
  5053. this.source = source;
  5054. this.i = 0;
  5055. AbstractObserver.call(this);
  5056. }
  5057. InnerObserver.prototype.next = function(x) {
  5058. var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
  5059. if (shouldYield === errorObj) {
  5060. return this.o.onError(shouldYield.e);
  5061. }
  5062. shouldYield && this.o.onNext(x);
  5063. };
  5064. InnerObserver.prototype.error = function (e) {
  5065. this.o.onError(e);
  5066. };
  5067. InnerObserver.prototype.completed = function () {
  5068. this.o.onCompleted();
  5069. };
  5070. return FilterObservable;
  5071. }(ObservableBase));
  5072. /**
  5073. * Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
  5074. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
  5075. * @param {Any} [thisArg] Object to use as this when executing callback.
  5076. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
  5077. */
  5078. observableProto.filter = observableProto.where = function (predicate, thisArg) {
  5079. return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
  5080. new FilterObservable(this, predicate, thisArg);
  5081. };
  5082. var ExtremaByObservable = (function (__super__) {
  5083. inherits(ExtremaByObservable, __super__);
  5084. function ExtremaByObservable(source, k, c) {
  5085. this.source = source;
  5086. this._k = k;
  5087. this._c = c;
  5088. __super__.call(this);
  5089. }
  5090. ExtremaByObservable.prototype.subscribeCore = function (o) {
  5091. return this.source.subscribe(new ExtremaByObserver(o, this._k, this._c));
  5092. };
  5093. return ExtremaByObservable;
  5094. }(ObservableBase));
  5095. var ExtremaByObserver = (function (__super__) {
  5096. inherits(ExtremaByObserver, __super__);
  5097. function ExtremaByObserver(o, k, c) {
  5098. this._o = o;
  5099. this._k = k;
  5100. this._c = c;
  5101. this._v = null;
  5102. this._hv = false;
  5103. this._l = [];
  5104. __super__.call(this);
  5105. }
  5106. ExtremaByObserver.prototype.next = function (x) {
  5107. var key = tryCatch(this._k)(x);
  5108. if (key === errorObj) { return this._o.onError(key.e); }
  5109. var comparison = 0;
  5110. if (!this._hv) {
  5111. this._hv = true;
  5112. this._v = key;
  5113. } else {
  5114. comparison = tryCatch(this._c)(key, this._v);
  5115. if (comparison === errorObj) { return this._o.onError(comparison.e); }
  5116. }
  5117. if (comparison > 0) {
  5118. this._v = key;
  5119. this._l = [];
  5120. }
  5121. if (comparison >= 0) { this._l.push(x); }
  5122. };
  5123. ExtremaByObserver.prototype.error = function (e) {
  5124. this._o.onError(e);
  5125. };
  5126. ExtremaByObserver.prototype.completed = function () {
  5127. this._o.onNext(this._l);
  5128. this._o.onCompleted();
  5129. };
  5130. return ExtremaByObserver;
  5131. }(AbstractObserver));
  5132. function firstOnly(x) {
  5133. if (x.length === 0) { throw new EmptyError(); }
  5134. return x[0];
  5135. }
  5136. var ReduceObservable = (function(__super__) {
  5137. inherits(ReduceObservable, __super__);
  5138. function ReduceObservable(source, accumulator, hasSeed, seed) {
  5139. this.source = source;
  5140. this.accumulator = accumulator;
  5141. this.hasSeed = hasSeed;
  5142. this.seed = seed;
  5143. __super__.call(this);
  5144. }
  5145. ReduceObservable.prototype.subscribeCore = function(observer) {
  5146. return this.source.subscribe(new ReduceObserver(observer,this));
  5147. };
  5148. return ReduceObservable;
  5149. }(ObservableBase));
  5150. var ReduceObserver = (function (__super__) {
  5151. inherits(ReduceObserver, __super__);
  5152. function ReduceObserver(o, parent) {
  5153. this._o = o;
  5154. this._p = parent;
  5155. this._fn = parent.accumulator;
  5156. this._hs = parent.hasSeed;
  5157. this._s = parent.seed;
  5158. this._ha = false;
  5159. this._a = null;
  5160. this._hv = false;
  5161. this._i = 0;
  5162. __super__.call(this);
  5163. }
  5164. ReduceObserver.prototype.next = function (x) {
  5165. !this._hv && (this._hv = true);
  5166. if (this._ha) {
  5167. this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
  5168. } else {
  5169. this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
  5170. this._ha = true;
  5171. }
  5172. if (this._a === errorObj) { return this._o.onError(this._a.e); }
  5173. this._i++;
  5174. };
  5175. ReduceObserver.prototype.error = function (e) {
  5176. this._o.onError(e);
  5177. };
  5178. ReduceObserver.prototype.completed = function () {
  5179. this._hv && this._o.onNext(this._a);
  5180. !this._hv && this._hs && this._o.onNext(this._s);
  5181. !this._hv && !this._hs && this._o.onError(new EmptyError());
  5182. this._o.onCompleted();
  5183. };
  5184. return ReduceObserver;
  5185. }(AbstractObserver));
  5186. /**
  5187. * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
  5188. * For aggregation behavior with incremental intermediate results, see Observable.scan.
  5189. * @param {Function} accumulator An accumulator function to be invoked on each element.
  5190. * @param {Any} [seed] The initial accumulator value.
  5191. * @returns {Observable} An observable sequence containing a single element with the final accumulator value.
  5192. */
  5193. observableProto.reduce = function () {
  5194. var hasSeed = false, seed, accumulator = arguments[0];
  5195. if (arguments.length === 2) {
  5196. hasSeed = true;
  5197. seed = arguments[1];
  5198. }
  5199. return new ReduceObservable(this, accumulator, hasSeed, seed);
  5200. };
  5201. var SomeObservable = (function (__super__) {
  5202. inherits(SomeObservable, __super__);
  5203. function SomeObservable(source, fn) {
  5204. this.source = source;
  5205. this._fn = fn;
  5206. __super__.call(this);
  5207. }
  5208. SomeObservable.prototype.subscribeCore = function (o) {
  5209. return this.source.subscribe(new SomeObserver(o, this._fn, this.source));
  5210. };
  5211. return SomeObservable;
  5212. }(ObservableBase));
  5213. var SomeObserver = (function (__super__) {
  5214. inherits(SomeObserver, __super__);
  5215. function SomeObserver(o, fn, s) {
  5216. this._o = o;
  5217. this._fn = fn;
  5218. this._s = s;
  5219. this._i = 0;
  5220. __super__.call(this);
  5221. }
  5222. SomeObserver.prototype.next = function (x) {
  5223. var result = tryCatch(this._fn)(x, this._i++, this._s);
  5224. if (result === errorObj) { return this._o.onError(result.e); }
  5225. if (Boolean(result)) {
  5226. this._o.onNext(true);
  5227. this._o.onCompleted();
  5228. }
  5229. };
  5230. SomeObserver.prototype.error = function (e) { this._o.onError(e); };
  5231. SomeObserver.prototype.completed = function () {
  5232. this._o.onNext(false);
  5233. this._o.onCompleted();
  5234. };
  5235. return SomeObserver;
  5236. }(AbstractObserver));
  5237. /**
  5238. * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
  5239. * @param {Function} [predicate] A function to test each element for a condition.
  5240. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
  5241. */
  5242. observableProto.some = function (predicate, thisArg) {
  5243. var fn = bindCallback(predicate, thisArg, 3);
  5244. return new SomeObservable(this, fn);
  5245. };
  5246. var IsEmptyObservable = (function (__super__) {
  5247. inherits(IsEmptyObservable, __super__);
  5248. function IsEmptyObservable(source) {
  5249. this.source = source;
  5250. __super__.call(this);
  5251. }
  5252. IsEmptyObservable.prototype.subscribeCore = function (o) {
  5253. return this.source.subscribe(new IsEmptyObserver(o));
  5254. };
  5255. return IsEmptyObservable;
  5256. }(ObservableBase));
  5257. var IsEmptyObserver = (function(__super__) {
  5258. inherits(IsEmptyObserver, __super__);
  5259. function IsEmptyObserver(o) {
  5260. this._o = o;
  5261. __super__.call(this);
  5262. }
  5263. IsEmptyObserver.prototype.next = function () {
  5264. this._o.onNext(false);
  5265. this._o.onCompleted();
  5266. };
  5267. IsEmptyObserver.prototype.error = function (e) { this._o.onError(e); };
  5268. IsEmptyObserver.prototype.completed = function () {
  5269. this._o.onNext(true);
  5270. this._o.onCompleted();
  5271. };
  5272. return IsEmptyObserver;
  5273. }(AbstractObserver));
  5274. /**
  5275. * Determines whether an observable sequence is empty.
  5276. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
  5277. */
  5278. observableProto.isEmpty = function () {
  5279. return new IsEmptyObservable(this);
  5280. };
  5281. var EveryObservable = (function (__super__) {
  5282. inherits(EveryObservable, __super__);
  5283. function EveryObservable(source, fn) {
  5284. this.source = source;
  5285. this._fn = fn;
  5286. __super__.call(this);
  5287. }
  5288. EveryObservable.prototype.subscribeCore = function (o) {
  5289. return this.source.subscribe(new EveryObserver(o, this._fn, this.source));
  5290. };
  5291. return EveryObservable;
  5292. }(ObservableBase));
  5293. var EveryObserver = (function (__super__) {
  5294. inherits(EveryObserver, __super__);
  5295. function EveryObserver(o, fn, s) {
  5296. this._o = o;
  5297. this._fn = fn;
  5298. this._s = s;
  5299. this._i = 0;
  5300. __super__.call(this);
  5301. }
  5302. EveryObserver.prototype.next = function (x) {
  5303. var result = tryCatch(this._fn)(x, this._i++, this._s);
  5304. if (result === errorObj) { return this._o.onError(result.e); }
  5305. if (!Boolean(result)) {
  5306. this._o.onNext(false);
  5307. this._o.onCompleted();
  5308. }
  5309. };
  5310. EveryObserver.prototype.error = function (e) { this._o.onError(e); };
  5311. EveryObserver.prototype.completed = function () {
  5312. this._o.onNext(true);
  5313. this._o.onCompleted();
  5314. };
  5315. return EveryObserver;
  5316. }(AbstractObserver));
  5317. /**
  5318. * Determines whether all elements of an observable sequence satisfy a condition.
  5319. * @param {Function} [predicate] A function to test each element for a condition.
  5320. * @param {Any} [thisArg] Object to use as this when executing callback.
  5321. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
  5322. */
  5323. observableProto.every = function (predicate, thisArg) {
  5324. var fn = bindCallback(predicate, thisArg, 3);
  5325. return new EveryObservable(this, fn);
  5326. };
  5327. var IncludesObservable = (function (__super__) {
  5328. inherits(IncludesObservable, __super__);
  5329. function IncludesObservable(source, elem, idx) {
  5330. var n = +idx || 0;
  5331. Math.abs(n) === Infinity && (n = 0);
  5332. this.source = source;
  5333. this._elem = elem;
  5334. this._n = n;
  5335. __super__.call(this);
  5336. }
  5337. IncludesObservable.prototype.subscribeCore = function (o) {
  5338. if (this._n < 0) {
  5339. o.onNext(false);
  5340. o.onCompleted();
  5341. return disposableEmpty;
  5342. }
  5343. return this.source.subscribe(new IncludesObserver(o, this._elem, this._n));
  5344. };
  5345. return IncludesObservable;
  5346. }(ObservableBase));
  5347. var IncludesObserver = (function (__super__) {
  5348. inherits(IncludesObserver, __super__);
  5349. function IncludesObserver(o, elem, n) {
  5350. this._o = o;
  5351. this._elem = elem;
  5352. this._n = n;
  5353. this._i = 0;
  5354. __super__.call(this);
  5355. }
  5356. function comparer(a, b) {
  5357. return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
  5358. }
  5359. IncludesObserver.prototype.next = function (x) {
  5360. if (this._i++ >= this._n && comparer(x, this._elem)) {
  5361. this._o.onNext(true);
  5362. this._o.onCompleted();
  5363. }
  5364. };
  5365. IncludesObserver.prototype.error = function (e) { this._o.onError(e); };
  5366. IncludesObserver.prototype.completed = function () { this._o.onNext(false); this._o.onCompleted(); };
  5367. return IncludesObserver;
  5368. }(AbstractObserver));
  5369. /**
  5370. * Determines whether an observable sequence includes a specified element with an optional equality comparer.
  5371. * @param searchElement The value to locate in the source sequence.
  5372. * @param {Number} [fromIndex] An equality comparer to compare elements.
  5373. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
  5374. */
  5375. observableProto.includes = function (searchElement, fromIndex) {
  5376. return new IncludesObservable(this, searchElement, fromIndex);
  5377. };
  5378. var CountObservable = (function (__super__) {
  5379. inherits(CountObservable, __super__);
  5380. function CountObservable(source, fn) {
  5381. this.source = source;
  5382. this._fn = fn;
  5383. __super__.call(this);
  5384. }
  5385. CountObservable.prototype.subscribeCore = function (o) {
  5386. return this.source.subscribe(new CountObserver(o, this._fn, this.source));
  5387. };
  5388. return CountObservable;
  5389. }(ObservableBase));
  5390. var CountObserver = (function (__super__) {
  5391. inherits(CountObserver, __super__);
  5392. function CountObserver(o, fn, s) {
  5393. this._o = o;
  5394. this._fn = fn;
  5395. this._s = s;
  5396. this._i = 0;
  5397. this._c = 0;
  5398. __super__.call(this);
  5399. }
  5400. CountObserver.prototype.next = function (x) {
  5401. if (this._fn) {
  5402. var result = tryCatch(this._fn)(x, this._i++, this._s);
  5403. if (result === errorObj) { return this._o.onError(result.e); }
  5404. Boolean(result) && (this._c++);
  5405. } else {
  5406. this._c++;
  5407. }
  5408. };
  5409. CountObserver.prototype.error = function (e) { this._o.onError(e); };
  5410. CountObserver.prototype.completed = function () {
  5411. this._o.onNext(this._c);
  5412. this._o.onCompleted();
  5413. };
  5414. return CountObserver;
  5415. }(AbstractObserver));
  5416. /**
  5417. * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
  5418. * @example
  5419. * res = source.count();
  5420. * res = source.count(function (x) { return x > 3; });
  5421. * @param {Function} [predicate]A function to test each element for a condition.
  5422. * @param {Any} [thisArg] Object to use as this when executing callback.
  5423. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
  5424. */
  5425. observableProto.count = function (predicate, thisArg) {
  5426. var fn = bindCallback(predicate, thisArg, 3);
  5427. return new CountObservable(this, fn);
  5428. };
  5429. var IndexOfObservable = (function (__super__) {
  5430. inherits(IndexOfObservable, __super__);
  5431. function IndexOfObservable(source, e, n) {
  5432. this.source = source;
  5433. this._e = e;
  5434. this._n = n;
  5435. __super__.call(this);
  5436. }
  5437. IndexOfObservable.prototype.subscribeCore = function (o) {
  5438. if (this._n < 0) {
  5439. o.onNext(-1);
  5440. o.onCompleted();
  5441. return disposableEmpty;
  5442. }
  5443. return this.source.subscribe(new IndexOfObserver(o, this._e, this._n));
  5444. };
  5445. return IndexOfObservable;
  5446. }(ObservableBase));
  5447. var IndexOfObserver = (function (__super__) {
  5448. inherits(IndexOfObserver, __super__);
  5449. function IndexOfObserver(o, e, n) {
  5450. this._o = o;
  5451. this._e = e;
  5452. this._n = n;
  5453. this._i = 0;
  5454. __super__.call(this);
  5455. }
  5456. IndexOfObserver.prototype.next = function (x) {
  5457. if (this._i >= this._n && x === this._e) {
  5458. this._o.onNext(this._i);
  5459. this._o.onCompleted();
  5460. }
  5461. this._i++;
  5462. };
  5463. IndexOfObserver.prototype.error = function (e) { this._o.onError(e); };
  5464. IndexOfObserver.prototype.completed = function () { this._o.onNext(-1); this._o.onCompleted(); };
  5465. return IndexOfObserver;
  5466. }(AbstractObserver));
  5467. /**
  5468. * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
  5469. * @param {Any} searchElement Element to locate in the array.
  5470. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
  5471. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
  5472. */
  5473. observableProto.indexOf = function(searchElement, fromIndex) {
  5474. var n = +fromIndex || 0;
  5475. Math.abs(n) === Infinity && (n = 0);
  5476. return new IndexOfObservable(this, searchElement, n);
  5477. };
  5478. var SumObservable = (function (__super__) {
  5479. inherits(SumObservable, __super__);
  5480. function SumObservable(source, fn) {
  5481. this.source = source;
  5482. this._fn = fn;
  5483. __super__.call(this);
  5484. }
  5485. SumObservable.prototype.subscribeCore = function (o) {
  5486. return this.source.subscribe(new SumObserver(o, this._fn, this.source));
  5487. };
  5488. return SumObservable;
  5489. }(ObservableBase));
  5490. var SumObserver = (function (__super__) {
  5491. inherits(SumObserver, __super__);
  5492. function SumObserver(o, fn, s) {
  5493. this._o = o;
  5494. this._fn = fn;
  5495. this._s = s;
  5496. this._i = 0;
  5497. this._c = 0;
  5498. __super__.call(this);
  5499. }
  5500. SumObserver.prototype.next = function (x) {
  5501. if (this._fn) {
  5502. var result = tryCatch(this._fn)(x, this._i++, this._s);
  5503. if (result === errorObj) { return this._o.onError(result.e); }
  5504. this._c += result;
  5505. } else {
  5506. this._c += x;
  5507. }
  5508. };
  5509. SumObserver.prototype.error = function (e) { this._o.onError(e); };
  5510. SumObserver.prototype.completed = function () {
  5511. this._o.onNext(this._c);
  5512. this._o.onCompleted();
  5513. };
  5514. return SumObserver;
  5515. }(AbstractObserver));
  5516. /**
  5517. * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
  5518. * @param {Function} [selector] A transform function to apply to each element.
  5519. * @param {Any} [thisArg] Object to use as this when executing callback.
  5520. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
  5521. */
  5522. observableProto.sum = function (keySelector, thisArg) {
  5523. var fn = bindCallback(keySelector, thisArg, 3);
  5524. return new SumObservable(this, fn);
  5525. };
  5526. /**
  5527. * Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
  5528. * @example
  5529. * var res = source.minBy(function (x) { return x.value; });
  5530. * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
  5531. * @param {Function} keySelector Key selector function.
  5532. * @param {Function} [comparer] Comparer used to compare key values.
  5533. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
  5534. */
  5535. observableProto.minBy = function (keySelector, comparer) {
  5536. comparer || (comparer = defaultSubComparer);
  5537. return new ExtremaByObservable(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
  5538. };
  5539. /**
  5540. * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
  5541. * @example
  5542. * var res = source.min();
  5543. * var res = source.min(function (x, y) { return x.value - y.value; });
  5544. * @param {Function} [comparer] Comparer used to compare elements.
  5545. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
  5546. */
  5547. observableProto.min = function (comparer) {
  5548. return this.minBy(identity, comparer).map(firstOnly);
  5549. };
  5550. /**
  5551. * Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
  5552. * @example
  5553. * var res = source.maxBy(function (x) { return x.value; });
  5554. * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
  5555. * @param {Function} keySelector Key selector function.
  5556. * @param {Function} [comparer] Comparer used to compare key values.
  5557. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
  5558. */
  5559. observableProto.maxBy = function (keySelector, comparer) {
  5560. comparer || (comparer = defaultSubComparer);
  5561. return new ExtremaByObservable(this, keySelector, comparer);
  5562. };
  5563. /**
  5564. * Returns the maximum value in an observable sequence according to the specified comparer.
  5565. * @example
  5566. * var res = source.max();
  5567. * var res = source.max(function (x, y) { return x.value - y.value; });
  5568. * @param {Function} [comparer] Comparer used to compare elements.
  5569. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
  5570. */
  5571. observableProto.max = function (comparer) {
  5572. return this.maxBy(identity, comparer).map(firstOnly);
  5573. };
  5574. var AverageObservable = (function (__super__) {
  5575. inherits(AverageObservable, __super__);
  5576. function AverageObservable(source, fn) {
  5577. this.source = source;
  5578. this._fn = fn;
  5579. __super__.call(this);
  5580. }
  5581. AverageObservable.prototype.subscribeCore = function (o) {
  5582. return this.source.subscribe(new AverageObserver(o, this._fn, this.source));
  5583. };
  5584. return AverageObservable;
  5585. }(ObservableBase));
  5586. var AverageObserver = (function(__super__) {
  5587. inherits(AverageObserver, __super__);
  5588. function AverageObserver(o, fn, s) {
  5589. this._o = o;
  5590. this._fn = fn;
  5591. this._s = s;
  5592. this._c = 0;
  5593. this._t = 0;
  5594. __super__.call(this);
  5595. }
  5596. AverageObserver.prototype.next = function (x) {
  5597. if(this._fn) {
  5598. var r = tryCatch(this._fn)(x, this._c++, this._s);
  5599. if (r === errorObj) { return this._o.onError(r.e); }
  5600. this._t += r;
  5601. } else {
  5602. this._c++;
  5603. this._t += x;
  5604. }
  5605. };
  5606. AverageObserver.prototype.error = function (e) { this._o.onError(e); };
  5607. AverageObserver.prototype.completed = function () {
  5608. if (this._c === 0) { return this._o.onError(new EmptyError()); }
  5609. this._o.onNext(this._t / this._c);
  5610. this._o.onCompleted();
  5611. };
  5612. return AverageObserver;
  5613. }(AbstractObserver));
  5614. /**
  5615. * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
  5616. * @param {Function} [selector] A transform function to apply to each element.
  5617. * @param {Any} [thisArg] Object to use as this when executing callback.
  5618. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
  5619. */
  5620. observableProto.average = function (keySelector, thisArg) {
  5621. var source = this, fn;
  5622. if (isFunction(keySelector)) {
  5623. fn = bindCallback(keySelector, thisArg, 3);
  5624. }
  5625. return new AverageObservable(source, fn);
  5626. };
  5627. /**
  5628. * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
  5629. *
  5630. * @example
  5631. * var res = res = source.sequenceEqual([1,2,3]);
  5632. * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
  5633. * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
  5634. * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
  5635. * @param {Observable} second Second observable sequence or array to compare.
  5636. * @param {Function} [comparer] Comparer used to compare elements of both sequences.
  5637. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
  5638. */
  5639. observableProto.sequenceEqual = function (second, comparer) {
  5640. var first = this;
  5641. comparer || (comparer = defaultComparer);
  5642. return new AnonymousObservable(function (o) {
  5643. var donel = false, doner = false, ql = [], qr = [];
  5644. var subscription1 = first.subscribe(function (x) {
  5645. if (qr.length > 0) {
  5646. var v = qr.shift();
  5647. var equal = tryCatch(comparer)(v, x);
  5648. if (equal === errorObj) { return o.onError(equal.e); }
  5649. if (!equal) {
  5650. o.onNext(false);
  5651. o.onCompleted();
  5652. }
  5653. } else if (doner) {
  5654. o.onNext(false);
  5655. o.onCompleted();
  5656. } else {
  5657. ql.push(x);
  5658. }
  5659. }, function(e) { o.onError(e); }, function () {
  5660. donel = true;
  5661. if (ql.length === 0) {
  5662. if (qr.length > 0) {
  5663. o.onNext(false);
  5664. o.onCompleted();
  5665. } else if (doner) {
  5666. o.onNext(true);
  5667. o.onCompleted();
  5668. }
  5669. }
  5670. });
  5671. (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
  5672. isPromise(second) && (second = observableFromPromise(second));
  5673. var subscription2 = second.subscribe(function (x) {
  5674. if (ql.length > 0) {
  5675. var v = ql.shift();
  5676. var equal = tryCatch(comparer)(v, x);
  5677. if (equal === errorObj) { return o.onError(equal.e); }
  5678. if (!equal) {
  5679. o.onNext(false);
  5680. o.onCompleted();
  5681. }
  5682. } else if (donel) {
  5683. o.onNext(false);
  5684. o.onCompleted();
  5685. } else {
  5686. qr.push(x);
  5687. }
  5688. }, function(e) { o.onError(e); }, function () {
  5689. doner = true;
  5690. if (qr.length === 0) {
  5691. if (ql.length > 0) {
  5692. o.onNext(false);
  5693. o.onCompleted();
  5694. } else if (donel) {
  5695. o.onNext(true);
  5696. o.onCompleted();
  5697. }
  5698. }
  5699. });
  5700. return new BinaryDisposable(subscription1, subscription2);
  5701. }, first);
  5702. };
  5703. var ElementAtObservable = (function (__super__) {
  5704. inherits(ElementAtObservable, __super__);
  5705. function ElementAtObservable(source, i, d) {
  5706. this.source = source;
  5707. this._i = i;
  5708. this._d = d;
  5709. __super__.call(this);
  5710. }
  5711. ElementAtObservable.prototype.subscribeCore = function (o) {
  5712. return this.source.subscribe(new ElementAtObserver(o, this._i, this._d));
  5713. };
  5714. return ElementAtObservable;
  5715. }(ObservableBase));
  5716. var ElementAtObserver = (function (__super__) {
  5717. inherits(ElementAtObserver, __super__);
  5718. function ElementAtObserver(o, i, d) {
  5719. this._o = o;
  5720. this._i = i;
  5721. this._d = d;
  5722. __super__.call(this);
  5723. }
  5724. ElementAtObserver.prototype.next = function (x) {
  5725. if (this._i-- === 0) {
  5726. this._o.onNext(x);
  5727. this._o.onCompleted();
  5728. }
  5729. };
  5730. ElementAtObserver.prototype.error = function (e) { this._o.onError(e); };
  5731. ElementAtObserver.prototype.completed = function () {
  5732. if (this._d === undefined) {
  5733. this._o.onError(new ArgumentOutOfRangeError());
  5734. } else {
  5735. this._o.onNext(this._d);
  5736. this._o.onCompleted();
  5737. }
  5738. };
  5739. return ElementAtObserver;
  5740. }(AbstractObserver));
  5741. /**
  5742. * Returns the element at a specified index in a sequence or default value if not found.
  5743. * @param {Number} index The zero-based index of the element to retrieve.
  5744. * @param {Any} [defaultValue] The default value to use if elementAt does not find a value.
  5745. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
  5746. */
  5747. observableProto.elementAt = function (index, defaultValue) {
  5748. if (index < 0) { throw new ArgumentOutOfRangeError(); }
  5749. return new ElementAtObservable(this, index, defaultValue);
  5750. };
  5751. var SingleObserver = (function(__super__) {
  5752. inherits(SingleObserver, __super__);
  5753. function SingleObserver(o, obj, s) {
  5754. this._o = o;
  5755. this._obj = obj;
  5756. this._s = s;
  5757. this._i = 0;
  5758. this._hv = false;
  5759. this._v = null;
  5760. __super__.call(this);
  5761. }
  5762. SingleObserver.prototype.next = function (x) {
  5763. var shouldYield = false;
  5764. if (this._obj.predicate) {
  5765. var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
  5766. if (res === errorObj) { return this._o.onError(res.e); }
  5767. Boolean(res) && (shouldYield = true);
  5768. } else if (!this._obj.predicate) {
  5769. shouldYield = true;
  5770. }
  5771. if (shouldYield) {
  5772. if (this._hv) {
  5773. return this._o.onError(new Error('Sequence contains more than one matching element'));
  5774. }
  5775. this._hv = true;
  5776. this._v = x;
  5777. }
  5778. };
  5779. SingleObserver.prototype.error = function (e) { this._o.onError(e); };
  5780. SingleObserver.prototype.completed = function () {
  5781. if (this._hv) {
  5782. this._o.onNext(this._v);
  5783. this._o.onCompleted();
  5784. }
  5785. else if (this._obj.defaultValue === undefined) {
  5786. this._o.onError(new EmptyError());
  5787. } else {
  5788. this._o.onNext(this._obj.defaultValue);
  5789. this._o.onCompleted();
  5790. }
  5791. };
  5792. return SingleObserver;
  5793. }(AbstractObserver));
  5794. /**
  5795. * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
  5796. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
  5797. */
  5798. observableProto.single = function (predicate, thisArg) {
  5799. var obj = {}, source = this;
  5800. if (typeof arguments[0] === 'object') {
  5801. obj = arguments[0];
  5802. } else {
  5803. obj = {
  5804. predicate: arguments[0],
  5805. thisArg: arguments[1],
  5806. defaultValue: arguments[2]
  5807. };
  5808. }
  5809. if (isFunction (obj.predicate)) {
  5810. var fn = obj.predicate;
  5811. obj.predicate = bindCallback(fn, obj.thisArg, 3);
  5812. }
  5813. return new AnonymousObservable(function (o) {
  5814. return source.subscribe(new SingleObserver(o, obj, source));
  5815. }, source);
  5816. };
  5817. var FirstObservable = (function (__super__) {
  5818. inherits(FirstObservable, __super__);
  5819. function FirstObservable(source, obj) {
  5820. this.source = source;
  5821. this._obj = obj;
  5822. __super__.call(this);
  5823. }
  5824. FirstObservable.prototype.subscribeCore = function (o) {
  5825. return this.source.subscribe(new FirstObserver(o, this._obj, this.source));
  5826. };
  5827. return FirstObservable;
  5828. }(ObservableBase));
  5829. var FirstObserver = (function(__super__) {
  5830. inherits(FirstObserver, __super__);
  5831. function FirstObserver(o, obj, s) {
  5832. this._o = o;
  5833. this._obj = obj;
  5834. this._s = s;
  5835. this._i = 0;
  5836. __super__.call(this);
  5837. }
  5838. FirstObserver.prototype.next = function (x) {
  5839. if (this._obj.predicate) {
  5840. var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
  5841. if (res === errorObj) { return this._o.onError(res.e); }
  5842. if (Boolean(res)) {
  5843. this._o.onNext(x);
  5844. this._o.onCompleted();
  5845. }
  5846. } else if (!this._obj.predicate) {
  5847. this._o.onNext(x);
  5848. this._o.onCompleted();
  5849. }
  5850. };
  5851. FirstObserver.prototype.error = function (e) { this._o.onError(e); };
  5852. FirstObserver.prototype.completed = function () {
  5853. if (this._obj.defaultValue === undefined) {
  5854. this._o.onError(new EmptyError());
  5855. } else {
  5856. this._o.onNext(this._obj.defaultValue);
  5857. this._o.onCompleted();
  5858. }
  5859. };
  5860. return FirstObserver;
  5861. }(AbstractObserver));
  5862. /**
  5863. * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
  5864. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
  5865. */
  5866. observableProto.first = function () {
  5867. var obj = {}, source = this;
  5868. if (typeof arguments[0] === 'object') {
  5869. obj = arguments[0];
  5870. } else {
  5871. obj = {
  5872. predicate: arguments[0],
  5873. thisArg: arguments[1],
  5874. defaultValue: arguments[2]
  5875. };
  5876. }
  5877. if (isFunction (obj.predicate)) {
  5878. var fn = obj.predicate;
  5879. obj.predicate = bindCallback(fn, obj.thisArg, 3);
  5880. }
  5881. return new FirstObservable(this, obj);
  5882. };
  5883. var LastObservable = (function (__super__) {
  5884. inherits(LastObservable, __super__);
  5885. function LastObservable(source, obj) {
  5886. this.source = source;
  5887. this._obj = obj;
  5888. __super__.call(this);
  5889. }
  5890. LastObservable.prototype.subscribeCore = function (o) {
  5891. return this.source.subscribe(new LastObserver(o, this._obj, this.source));
  5892. };
  5893. return LastObservable;
  5894. }(ObservableBase));
  5895. var LastObserver = (function(__super__) {
  5896. inherits(LastObserver, __super__);
  5897. function LastObserver(o, obj, s) {
  5898. this._o = o;
  5899. this._obj = obj;
  5900. this._s = s;
  5901. this._i = 0;
  5902. this._hv = false;
  5903. this._v = null;
  5904. __super__.call(this);
  5905. }
  5906. LastObserver.prototype.next = function (x) {
  5907. var shouldYield = false;
  5908. if (this._obj.predicate) {
  5909. var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
  5910. if (res === errorObj) { return this._o.onError(res.e); }
  5911. Boolean(res) && (shouldYield = true);
  5912. } else if (!this._obj.predicate) {
  5913. shouldYield = true;
  5914. }
  5915. if (shouldYield) {
  5916. this._hv = true;
  5917. this._v = x;
  5918. }
  5919. };
  5920. LastObserver.prototype.error = function (e) { this._o.onError(e); };
  5921. LastObserver.prototype.completed = function () {
  5922. if (this._hv) {
  5923. this._o.onNext(this._v);
  5924. this._o.onCompleted();
  5925. }
  5926. else if (this._obj.defaultValue === undefined) {
  5927. this._o.onError(new EmptyError());
  5928. } else {
  5929. this._o.onNext(this._obj.defaultValue);
  5930. this._o.onCompleted();
  5931. }
  5932. };
  5933. return LastObserver;
  5934. }(AbstractObserver));
  5935. /**
  5936. * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
  5937. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
  5938. */
  5939. observableProto.last = function () {
  5940. var obj = {}, source = this;
  5941. if (typeof arguments[0] === 'object') {
  5942. obj = arguments[0];
  5943. } else {
  5944. obj = {
  5945. predicate: arguments[0],
  5946. thisArg: arguments[1],
  5947. defaultValue: arguments[2]
  5948. };
  5949. }
  5950. if (isFunction (obj.predicate)) {
  5951. var fn = obj.predicate;
  5952. obj.predicate = bindCallback(fn, obj.thisArg, 3);
  5953. }
  5954. return new LastObservable(this, obj);
  5955. };
  5956. var FindValueObserver = (function(__super__) {
  5957. inherits(FindValueObserver, __super__);
  5958. function FindValueObserver(observer, source, callback, yieldIndex) {
  5959. this._o = observer;
  5960. this._s = source;
  5961. this._cb = callback;
  5962. this._y = yieldIndex;
  5963. this._i = 0;
  5964. __super__.call(this);
  5965. }
  5966. FindValueObserver.prototype.next = function (x) {
  5967. var shouldRun = tryCatch(this._cb)(x, this._i, this._s);
  5968. if (shouldRun === errorObj) { return this._o.onError(shouldRun.e); }
  5969. if (shouldRun) {
  5970. this._o.onNext(this._y ? this._i : x);
  5971. this._o.onCompleted();
  5972. } else {
  5973. this._i++;
  5974. }
  5975. };
  5976. FindValueObserver.prototype.error = function (e) {
  5977. this._o.onError(e);
  5978. };
  5979. FindValueObserver.prototype.completed = function () {
  5980. this._y && this._o.onNext(-1);
  5981. this._o.onCompleted();
  5982. };
  5983. return FindValueObserver;
  5984. }(AbstractObserver));
  5985. function findValue (source, predicate, thisArg, yieldIndex) {
  5986. var callback = bindCallback(predicate, thisArg, 3);
  5987. return new AnonymousObservable(function (o) {
  5988. return source.subscribe(new FindValueObserver(o, source, callback, yieldIndex));
  5989. }, source);
  5990. }
  5991. /**
  5992. * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
  5993. * @param {Function} predicate The predicate that defines the conditions of the element to search for.
  5994. * @param {Any} [thisArg] Object to use as `this` when executing the predicate.
  5995. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
  5996. */
  5997. observableProto.find = function (predicate, thisArg) {
  5998. return findValue(this, predicate, thisArg, false);
  5999. };
  6000. /**
  6001. * Searches for an element that matches the conditions defined by the specified predicate, and returns
  6002. * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
  6003. * @param {Function} predicate The predicate that defines the conditions of the element to search for.
  6004. * @param {Any} [thisArg] Object to use as `this` when executing the predicate.
  6005. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
  6006. */
  6007. observableProto.findIndex = function (predicate, thisArg) {
  6008. return findValue(this, predicate, thisArg, true);
  6009. };
  6010. var ToSetObservable = (function (__super__) {
  6011. inherits(ToSetObservable, __super__);
  6012. function ToSetObservable(source) {
  6013. this.source = source;
  6014. __super__.call(this);
  6015. }
  6016. ToSetObservable.prototype.subscribeCore = function (o) {
  6017. return this.source.subscribe(new ToSetObserver(o));
  6018. };
  6019. return ToSetObservable;
  6020. }(ObservableBase));
  6021. var ToSetObserver = (function (__super__) {
  6022. inherits(ToSetObserver, __super__);
  6023. function ToSetObserver(o) {
  6024. this._o = o;
  6025. this._s = new root.Set();
  6026. __super__.call(this);
  6027. }
  6028. ToSetObserver.prototype.next = function (x) {
  6029. this._s.add(x);
  6030. };
  6031. ToSetObserver.prototype.error = function (e) {
  6032. this._o.onError(e);
  6033. };
  6034. ToSetObserver.prototype.completed = function () {
  6035. this._o.onNext(this._s);
  6036. this._o.onCompleted();
  6037. };
  6038. return ToSetObserver;
  6039. }(AbstractObserver));
  6040. /**
  6041. * Converts the observable sequence to a Set if it exists.
  6042. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
  6043. */
  6044. observableProto.toSet = function () {
  6045. if (typeof root.Set === 'undefined') { throw new TypeError(); }
  6046. return new ToSetObservable(this);
  6047. };
  6048. var ToMapObservable = (function (__super__) {
  6049. inherits(ToMapObservable, __super__);
  6050. function ToMapObservable(source, k, e) {
  6051. this.source = source;
  6052. this._k = k;
  6053. this._e = e;
  6054. __super__.call(this);
  6055. }
  6056. ToMapObservable.prototype.subscribeCore = function (o) {
  6057. return this.source.subscribe(new ToMapObserver(o, this._k, this._e));
  6058. };
  6059. return ToMapObservable;
  6060. }(ObservableBase));
  6061. var ToMapObserver = (function (__super__) {
  6062. inherits(ToMapObserver, __super__);
  6063. function ToMapObserver(o, k, e) {
  6064. this._o = o;
  6065. this._k = k;
  6066. this._e = e;
  6067. this._m = new root.Map();
  6068. __super__.call(this);
  6069. }
  6070. ToMapObserver.prototype.next = function (x) {
  6071. var key = tryCatch(this._k)(x);
  6072. if (key === errorObj) { return this._o.onError(key.e); }
  6073. var elem = x;
  6074. if (this._e) {
  6075. elem = tryCatch(this._e)(x);
  6076. if (elem === errorObj) { return this._o.onError(elem.e); }
  6077. }
  6078. this._m.set(key, elem);
  6079. };
  6080. ToMapObserver.prototype.error = function (e) {
  6081. this._o.onError(e);
  6082. };
  6083. ToMapObserver.prototype.completed = function () {
  6084. this._o.onNext(this._m);
  6085. this._o.onCompleted();
  6086. };
  6087. return ToMapObserver;
  6088. }(AbstractObserver));
  6089. /**
  6090. * Converts the observable sequence to a Map if it exists.
  6091. * @param {Function} keySelector A function which produces the key for the Map.
  6092. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
  6093. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
  6094. */
  6095. observableProto.toMap = function (keySelector, elementSelector) {
  6096. if (typeof root.Map === 'undefined') { throw new TypeError(); }
  6097. return new ToMapObservable(this, keySelector, elementSelector);
  6098. };
  6099. var SliceObservable = (function (__super__) {
  6100. inherits(SliceObservable, __super__);
  6101. function SliceObservable(source, b, e) {
  6102. this.source = source;
  6103. this._b = b;
  6104. this._e = e;
  6105. __super__.call(this);
  6106. }
  6107. SliceObservable.prototype.subscribeCore = function (o) {
  6108. return this.source.subscribe(new SliceObserver(o, this._b, this._e));
  6109. };
  6110. return SliceObservable;
  6111. }(ObservableBase));
  6112. var SliceObserver = (function (__super__) {
  6113. inherits(SliceObserver, __super__);
  6114. function SliceObserver(o, b, e) {
  6115. this._o = o;
  6116. this._b = b;
  6117. this._e = e;
  6118. this._i = 0;
  6119. __super__.call(this);
  6120. }
  6121. SliceObserver.prototype.next = function (x) {
  6122. if (this._i >= this._b) {
  6123. if (this._e === this._i) {
  6124. this._o.onCompleted();
  6125. } else {
  6126. this._o.onNext(x);
  6127. }
  6128. }
  6129. this._i++;
  6130. };
  6131. SliceObserver.prototype.error = function (e) { this._o.onError(e); };
  6132. SliceObserver.prototype.completed = function () { this._o.onCompleted(); };
  6133. return SliceObserver;
  6134. }(AbstractObserver));
  6135. /*
  6136. * The slice() method returns a shallow copy of a portion of an Observable into a new Observable object.
  6137. * Unlike the array version, this does not support negative numbers for being or end.
  6138. * @param {Number} [begin] Zero-based index at which to begin extraction. If omitted, this will default to zero.
  6139. * @param {Number} [end] Zero-based index at which to end extraction. slice extracts up to but not including end.
  6140. * If omitted, this will emit the rest of the Observable object.
  6141. * @returns {Observable} A shallow copy of a portion of an Observable into a new Observable object.
  6142. */
  6143. observableProto.slice = function (begin, end) {
  6144. var start = begin || 0;
  6145. if (start < 0) { throw new Rx.ArgumentOutOfRangeError(); }
  6146. if (typeof end === 'number' && end < start) {
  6147. throw new Rx.ArgumentOutOfRangeError();
  6148. }
  6149. return new SliceObservable(this, start, end);
  6150. };
  6151. var LastIndexOfObservable = (function (__super__) {
  6152. inherits(LastIndexOfObservable, __super__);
  6153. function LastIndexOfObservable(source, e, n) {
  6154. this.source = source;
  6155. this._e = e;
  6156. this._n = n;
  6157. __super__.call(this);
  6158. }
  6159. LastIndexOfObservable.prototype.subscribeCore = function (o) {
  6160. if (this._n < 0) {
  6161. o.onNext(-1);
  6162. o.onCompleted();
  6163. return disposableEmpty;
  6164. }
  6165. return this.source.subscribe(new LastIndexOfObserver(o, this._e, this._n));
  6166. };
  6167. return LastIndexOfObservable;
  6168. }(ObservableBase));
  6169. var LastIndexOfObserver = (function (__super__) {
  6170. inherits(LastIndexOfObserver, __super__);
  6171. function LastIndexOfObserver(o, e, n) {
  6172. this._o = o;
  6173. this._e = e;
  6174. this._n = n;
  6175. this._v = 0;
  6176. this._hv = false;
  6177. this._i = 0;
  6178. __super__.call(this);
  6179. }
  6180. LastIndexOfObserver.prototype.next = function (x) {
  6181. if (this._i >= this._n && x === this._e) {
  6182. this._hv = true;
  6183. this._v = this._i;
  6184. }
  6185. this._i++;
  6186. };
  6187. LastIndexOfObserver.prototype.error = function (e) { this._o.onError(e); };
  6188. LastIndexOfObserver.prototype.completed = function () {
  6189. if (this._hv) {
  6190. this._o.onNext(this._v);
  6191. } else {
  6192. this._o.onNext(-1);
  6193. }
  6194. this._o.onCompleted();
  6195. };
  6196. return LastIndexOfObserver;
  6197. }(AbstractObserver));
  6198. /**
  6199. * Returns the last index at which a given element can be found in the observable sequence, or -1 if it is not present.
  6200. * @param {Any} searchElement Element to locate in the array.
  6201. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
  6202. * @returns {Observable} And observable sequence containing the last index at which a given element can be found in the observable sequence, or -1 if it is not present.
  6203. */
  6204. observableProto.lastIndexOf = function(searchElement, fromIndex) {
  6205. var n = +fromIndex || 0;
  6206. Math.abs(n) === Infinity && (n = 0);
  6207. return new LastIndexOfObservable(this, searchElement, n);
  6208. };
  6209. Observable.wrap = function (fn) {
  6210. function createObservable() {
  6211. return Observable.spawn.call(this, fn.apply(this, arguments));
  6212. }
  6213. createObservable.__generatorFunction__ = fn;
  6214. return createObservable;
  6215. };
  6216. var spawn = Observable.spawn = function () {
  6217. var gen = arguments[0], self = this, args = [];
  6218. for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
  6219. return new AnonymousObservable(function (o) {
  6220. var g = new CompositeDisposable();
  6221. if (isFunction(gen)) { gen = gen.apply(self, args); }
  6222. if (!gen || !isFunction(gen.next)) {
  6223. o.onNext(gen);
  6224. return o.onCompleted();
  6225. }
  6226. function processGenerator(res) {
  6227. var ret = tryCatch(gen.next).call(gen, res);
  6228. if (ret === errorObj) { return o.onError(ret.e); }
  6229. next(ret);
  6230. }
  6231. processGenerator();
  6232. function onError(err) {
  6233. var ret = tryCatch(gen.next).call(gen, err);
  6234. if (ret === errorObj) { return o.onError(ret.e); }
  6235. next(ret);
  6236. }
  6237. function next(ret) {
  6238. if (ret.done) {
  6239. o.onNext(ret.value);
  6240. o.onCompleted();
  6241. return;
  6242. }
  6243. var obs = toObservable.call(self, ret.value);
  6244. var value = null;
  6245. var hasValue = false;
  6246. if (Observable.isObservable(obs)) {
  6247. g.add(obs.subscribe(function(val) {
  6248. hasValue = true;
  6249. value = val;
  6250. }, onError, function() {
  6251. hasValue && processGenerator(value);
  6252. }));
  6253. } else {
  6254. onError(new TypeError('type not supported'));
  6255. }
  6256. }
  6257. return g;
  6258. });
  6259. };
  6260. function toObservable(obj) {
  6261. if (!obj) { return obj; }
  6262. if (Observable.isObservable(obj)) { return obj; }
  6263. if (isPromise(obj)) { return Observable.fromPromise(obj); }
  6264. if (isGeneratorFunction(obj) || isGenerator(obj)) { return spawn.call(this, obj); }
  6265. if (isFunction(obj)) { return thunkToObservable.call(this, obj); }
  6266. if (isArrayLike(obj) || isIterable(obj)) { return arrayToObservable.call(this, obj); }
  6267. if (isObject(obj)) {return objectToObservable.call(this, obj);}
  6268. return obj;
  6269. }
  6270. function arrayToObservable (obj) {
  6271. return Observable.from(obj).concatMap(function(o) {
  6272. if(Observable.isObservable(o) || isObject(o)) {
  6273. return toObservable.call(null, o);
  6274. } else {
  6275. return Rx.Observable.just(o);
  6276. }
  6277. }).toArray();
  6278. }
  6279. function objectToObservable (obj) {
  6280. var results = new obj.constructor(), keys = Object.keys(obj), observables = [];
  6281. for (var i = 0, len = keys.length; i < len; i++) {
  6282. var key = keys[i];
  6283. var observable = toObservable.call(this, obj[key]);
  6284. if(observable && Observable.isObservable(observable)) {
  6285. defer(observable, key);
  6286. } else {
  6287. results[key] = obj[key];
  6288. }
  6289. }
  6290. return Observable.forkJoin.apply(Observable, observables).map(function() {
  6291. return results;
  6292. });
  6293. function defer (observable, key) {
  6294. results[key] = undefined;
  6295. observables.push(observable.map(function (next) {
  6296. results[key] = next;
  6297. }));
  6298. }
  6299. }
  6300. function thunkToObservable(fn) {
  6301. var self = this;
  6302. return new AnonymousObservable(function (o) {
  6303. fn.call(self, function () {
  6304. var err = arguments[0], res = arguments[1];
  6305. if (err) { return o.onError(err); }
  6306. if (arguments.length > 2) {
  6307. var args = [];
  6308. for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
  6309. res = args;
  6310. }
  6311. o.onNext(res);
  6312. o.onCompleted();
  6313. });
  6314. });
  6315. }
  6316. function isGenerator(obj) {
  6317. return isFunction (obj.next) && isFunction (obj['throw']);
  6318. }
  6319. function isGeneratorFunction(obj) {
  6320. var ctor = obj.constructor;
  6321. if (!ctor) { return false; }
  6322. if (ctor.name === 'GeneratorFunction' || ctor.displayName === 'GeneratorFunction') { return true; }
  6323. return isGenerator(ctor.prototype);
  6324. }
  6325. function isObject(val) {
  6326. return Object == val.constructor;
  6327. }
  6328. /**
  6329. * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
  6330. *
  6331. * @example
  6332. * var res = Rx.Observable.start(function () { console.log('hello'); });
  6333. * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
  6334. * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
  6335. *
  6336. * @param {Function} func Function to run asynchronously.
  6337. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
  6338. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
  6339. * @returns {Observable} An observable sequence exposing the function's result value, or an exception.
  6340. *
  6341. * Remarks
  6342. * * The function is called immediately, not during the subscription of the resulting sequence.
  6343. * * Multiple subscriptions to the resulting sequence can observe the function's result.
  6344. */
  6345. Observable.start = function (func, context, scheduler) {
  6346. return observableToAsync(func, context, scheduler)();
  6347. };
  6348. /**
  6349. * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
  6350. * @param {Function} function Function to convert to an asynchronous function.
  6351. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
  6352. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
  6353. * @returns {Function} Asynchronous function.
  6354. */
  6355. var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
  6356. isScheduler(scheduler) || (scheduler = defaultScheduler);
  6357. return function () {
  6358. var args = arguments,
  6359. subject = new AsyncSubject();
  6360. scheduler.schedule(null, function () {
  6361. var result;
  6362. try {
  6363. result = func.apply(context, args);
  6364. } catch (e) {
  6365. subject.onError(e);
  6366. return;
  6367. }
  6368. subject.onNext(result);
  6369. subject.onCompleted();
  6370. });
  6371. return subject.asObservable();
  6372. };
  6373. };
  6374. function createCbObservable(fn, ctx, selector, args) {
  6375. var o = new AsyncSubject();
  6376. args.push(createCbHandler(o, ctx, selector));
  6377. fn.apply(ctx, args);
  6378. return o.asObservable();
  6379. }
  6380. function createCbHandler(o, ctx, selector) {
  6381. return function handler () {
  6382. var len = arguments.length, results = new Array(len);
  6383. for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
  6384. if (isFunction(selector)) {
  6385. results = tryCatch(selector).apply(ctx, results);
  6386. if (results === errorObj) { return o.onError(results.e); }
  6387. o.onNext(results);
  6388. } else {
  6389. if (results.length <= 1) {
  6390. o.onNext(results[0]);
  6391. } else {
  6392. o.onNext(results);
  6393. }
  6394. }
  6395. o.onCompleted();
  6396. };
  6397. }
  6398. /**
  6399. * Converts a callback function to an observable sequence.
  6400. *
  6401. * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence.
  6402. * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
  6403. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
  6404. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
  6405. */
  6406. Observable.fromCallback = function (fn, ctx, selector) {
  6407. return function () {
  6408. typeof ctx === 'undefined' && (ctx = this);
  6409. var len = arguments.length, args = new Array(len)
  6410. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  6411. return createCbObservable(fn, ctx, selector, args);
  6412. };
  6413. };
  6414. function createNodeObservable(fn, ctx, selector, args) {
  6415. var o = new AsyncSubject();
  6416. args.push(createNodeHandler(o, ctx, selector));
  6417. fn.apply(ctx, args);
  6418. return o.asObservable();
  6419. }
  6420. function createNodeHandler(o, ctx, selector) {
  6421. return function handler () {
  6422. var err = arguments[0];
  6423. if (err) { return o.onError(err); }
  6424. var len = arguments.length, results = [];
  6425. for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
  6426. if (isFunction(selector)) {
  6427. var results = tryCatch(selector).apply(ctx, results);
  6428. if (results === errorObj) { return o.onError(results.e); }
  6429. o.onNext(results);
  6430. } else {
  6431. if (results.length <= 1) {
  6432. o.onNext(results[0]);
  6433. } else {
  6434. o.onNext(results);
  6435. }
  6436. }
  6437. o.onCompleted();
  6438. };
  6439. }
  6440. /**
  6441. * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
  6442. * @param {Function} fn The function to call
  6443. * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
  6444. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
  6445. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
  6446. */
  6447. Observable.fromNodeCallback = function (fn, ctx, selector) {
  6448. return function () {
  6449. typeof ctx === 'undefined' && (ctx = this);
  6450. var len = arguments.length, args = new Array(len);
  6451. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  6452. return createNodeObservable(fn, ctx, selector, args);
  6453. };
  6454. };
  6455. function isNodeList(el) {
  6456. if (root.StaticNodeList) {
  6457. // IE8 Specific
  6458. // instanceof is slower than Object#toString, but Object#toString will not work as intended in IE8
  6459. return el instanceof root.StaticNodeList || el instanceof root.NodeList;
  6460. } else {
  6461. return Object.prototype.toString.call(el) === '[object NodeList]';
  6462. }
  6463. }
  6464. function ListenDisposable(e, n, fn) {
  6465. this._e = e;
  6466. this._n = n;
  6467. this._fn = fn;
  6468. this._e.addEventListener(this._n, this._fn, false);
  6469. this.isDisposed = false;
  6470. }
  6471. ListenDisposable.prototype.dispose = function () {
  6472. if (!this.isDisposed) {
  6473. this._e.removeEventListener(this._n, this._fn, false);
  6474. this.isDisposed = true;
  6475. }
  6476. };
  6477. function createEventListener (el, eventName, handler) {
  6478. var disposables = new CompositeDisposable();
  6479. // Asume NodeList or HTMLCollection
  6480. var elemToString = Object.prototype.toString.call(el);
  6481. if (isNodeList(el) || elemToString === '[object HTMLCollection]') {
  6482. for (var i = 0, len = el.length; i < len; i++) {
  6483. disposables.add(createEventListener(el.item(i), eventName, handler));
  6484. }
  6485. } else if (el) {
  6486. disposables.add(new ListenDisposable(el, eventName, handler));
  6487. }
  6488. return disposables;
  6489. }
  6490. /**
  6491. * Configuration option to determine whether to use native events only
  6492. */
  6493. Rx.config.useNativeEvents = false;
  6494. var EventObservable = (function(__super__) {
  6495. inherits(EventObservable, __super__);
  6496. function EventObservable(el, name, fn) {
  6497. this._el = el;
  6498. this._n = name;
  6499. this._fn = fn;
  6500. __super__.call(this);
  6501. }
  6502. function createHandler(o, fn) {
  6503. return function handler () {
  6504. var results = arguments[0];
  6505. if (isFunction(fn)) {
  6506. results = tryCatch(fn).apply(null, arguments);
  6507. if (results === errorObj) { return o.onError(results.e); }
  6508. }
  6509. o.onNext(results);
  6510. };
  6511. }
  6512. EventObservable.prototype.subscribeCore = function (o) {
  6513. return createEventListener(
  6514. this._el,
  6515. this._n,
  6516. createHandler(o, this._fn));
  6517. };
  6518. return EventObservable;
  6519. }(ObservableBase));
  6520. /**
  6521. * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
  6522. * @param {Object} element The DOMElement or NodeList to attach a listener.
  6523. * @param {String} eventName The event name to attach the observable sequence.
  6524. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
  6525. * @returns {Observable} An observable sequence of events from the specified element and the specified event.
  6526. */
  6527. Observable.fromEvent = function (element, eventName, selector) {
  6528. // Node.js specific
  6529. if (element.addListener) {
  6530. return fromEventPattern(
  6531. function (h) { element.addListener(eventName, h); },
  6532. function (h) { element.removeListener(eventName, h); },
  6533. selector);
  6534. }
  6535. // Use only if non-native events are allowed
  6536. if (!Rx.config.useNativeEvents) {
  6537. // Handles jq, Angular.js, Zepto, Marionette, Ember.js
  6538. if (typeof element.on === 'function' && typeof element.off === 'function') {
  6539. return fromEventPattern(
  6540. function (h) { element.on(eventName, h); },
  6541. function (h) { element.off(eventName, h); },
  6542. selector);
  6543. }
  6544. }
  6545. return new EventObservable(element, eventName, selector).publish().refCount();
  6546. };
  6547. var EventPatternObservable = (function(__super__) {
  6548. inherits(EventPatternObservable, __super__);
  6549. function EventPatternObservable(add, del, fn) {
  6550. this._add = add;
  6551. this._del = del;
  6552. this._fn = fn;
  6553. __super__.call(this);
  6554. }
  6555. function createHandler(o, fn) {
  6556. return function handler () {
  6557. var results = arguments[0];
  6558. if (isFunction(fn)) {
  6559. results = tryCatch(fn).apply(null, arguments);
  6560. if (results === errorObj) { return o.onError(results.e); }
  6561. }
  6562. o.onNext(results);
  6563. };
  6564. }
  6565. EventPatternObservable.prototype.subscribeCore = function (o) {
  6566. var fn = createHandler(o, this._fn);
  6567. var returnValue = this._add(fn);
  6568. return new EventPatternDisposable(this._del, fn, returnValue);
  6569. };
  6570. function EventPatternDisposable(del, fn, ret) {
  6571. this._del = del;
  6572. this._fn = fn;
  6573. this._ret = ret;
  6574. this.isDisposed = false;
  6575. }
  6576. EventPatternDisposable.prototype.dispose = function () {
  6577. if(!this.isDisposed) {
  6578. isFunction(this._del) && this._del(this._fn, this._ret);
  6579. this.isDisposed = true;
  6580. }
  6581. };
  6582. return EventPatternObservable;
  6583. }(ObservableBase));
  6584. /**
  6585. * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
  6586. * @param {Function} addHandler The function to add a handler to the emitter.
  6587. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
  6588. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
  6589. * @returns {Observable} An observable sequence which wraps an event from an event emitter
  6590. */
  6591. var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
  6592. return new EventPatternObservable(addHandler, removeHandler, selector).publish().refCount();
  6593. };
  6594. /**
  6595. * Invokes the asynchronous function, surfacing the result through an observable sequence.
  6596. * @param {Function} functionAsync Asynchronous function which returns a Promise to run.
  6597. * @returns {Observable} An observable sequence exposing the function's result value, or an exception.
  6598. */
  6599. Observable.startAsync = function (functionAsync) {
  6600. var promise = tryCatch(functionAsync)();
  6601. if (promise === errorObj) { return observableThrow(promise.e); }
  6602. return observableFromPromise(promise);
  6603. };
  6604. var PausableObservable = (function (__super__) {
  6605. inherits(PausableObservable, __super__);
  6606. function PausableObservable(source, pauser) {
  6607. this.source = source;
  6608. this.controller = new Subject();
  6609. this.paused = true;
  6610. if (pauser && pauser.subscribe) {
  6611. this.pauser = this.controller.merge(pauser);
  6612. } else {
  6613. this.pauser = this.controller;
  6614. }
  6615. __super__.call(this);
  6616. }
  6617. PausableObservable.prototype._subscribe = function (o) {
  6618. var conn = this.source.publish(),
  6619. subscription = conn.subscribe(o),
  6620. connection = disposableEmpty;
  6621. var pausable = this.pauser.startWith(!this.paused).distinctUntilChanged().subscribe(function (b) {
  6622. if (b) {
  6623. connection = conn.connect();
  6624. } else {
  6625. connection.dispose();
  6626. connection = disposableEmpty;
  6627. }
  6628. });
  6629. return new NAryDisposable([subscription, connection, pausable]);
  6630. };
  6631. PausableObservable.prototype.pause = function () {
  6632. this.paused = true;
  6633. this.controller.onNext(false);
  6634. };
  6635. PausableObservable.prototype.resume = function () {
  6636. this.paused = false;
  6637. this.controller.onNext(true);
  6638. };
  6639. return PausableObservable;
  6640. }(Observable));
  6641. /**
  6642. * Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
  6643. * @example
  6644. * var pauser = new Rx.Subject();
  6645. * var source = Rx.Observable.interval(100).pausable(pauser);
  6646. * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
  6647. * @returns {Observable} The observable sequence which is paused based upon the pauser.
  6648. */
  6649. observableProto.pausable = function (pauser) {
  6650. return new PausableObservable(this, pauser);
  6651. };
  6652. function combineLatestSource(source, subject, resultSelector) {
  6653. return new AnonymousObservable(function (o) {
  6654. var hasValue = [false, false],
  6655. hasValueAll = false,
  6656. isDone = false,
  6657. values = new Array(2),
  6658. err;
  6659. function next(x, i) {
  6660. values[i] = x;
  6661. hasValue[i] = true;
  6662. if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
  6663. if (err) { return o.onError(err); }
  6664. var res = tryCatch(resultSelector).apply(null, values);
  6665. if (res === errorObj) { return o.onError(res.e); }
  6666. o.onNext(res);
  6667. }
  6668. isDone && values[1] && o.onCompleted();
  6669. }
  6670. return new BinaryDisposable(
  6671. source.subscribe(
  6672. function (x) {
  6673. next(x, 0);
  6674. },
  6675. function (e) {
  6676. if (values[1]) {
  6677. o.onError(e);
  6678. } else {
  6679. err = e;
  6680. }
  6681. },
  6682. function () {
  6683. isDone = true;
  6684. values[1] && o.onCompleted();
  6685. }),
  6686. subject.subscribe(
  6687. function (x) {
  6688. next(x, 1);
  6689. },
  6690. function (e) { o.onError(e); },
  6691. function () {
  6692. isDone = true;
  6693. next(true, 1);
  6694. })
  6695. );
  6696. }, source);
  6697. }
  6698. var PausableBufferedObservable = (function (__super__) {
  6699. inherits(PausableBufferedObservable, __super__);
  6700. function PausableBufferedObservable(source, pauser) {
  6701. this.source = source;
  6702. this.controller = new Subject();
  6703. this.paused = true;
  6704. if (pauser && pauser.subscribe) {
  6705. this.pauser = this.controller.merge(pauser);
  6706. } else {
  6707. this.pauser = this.controller;
  6708. }
  6709. __super__.call(this);
  6710. }
  6711. PausableBufferedObservable.prototype._subscribe = function (o) {
  6712. var q = [], previousShouldFire;
  6713. function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } }
  6714. var subscription =
  6715. combineLatestSource(
  6716. this.source,
  6717. this.pauser.startWith(!this.paused).distinctUntilChanged(),
  6718. function (data, shouldFire) {
  6719. return { data: data, shouldFire: shouldFire };
  6720. })
  6721. .subscribe(
  6722. function (results) {
  6723. if (previousShouldFire !== undefined && results.shouldFire !== previousShouldFire) {
  6724. previousShouldFire = results.shouldFire;
  6725. // change in shouldFire
  6726. if (results.shouldFire) { drainQueue(); }
  6727. } else {
  6728. previousShouldFire = results.shouldFire;
  6729. // new data
  6730. if (results.shouldFire) {
  6731. o.onNext(results.data);
  6732. } else {
  6733. q.push(results.data);
  6734. }
  6735. }
  6736. },
  6737. function (err) {
  6738. drainQueue();
  6739. o.onError(err);
  6740. },
  6741. function () {
  6742. drainQueue();
  6743. o.onCompleted();
  6744. }
  6745. );
  6746. return subscription;
  6747. };
  6748. PausableBufferedObservable.prototype.pause = function () {
  6749. this.paused = true;
  6750. this.controller.onNext(false);
  6751. };
  6752. PausableBufferedObservable.prototype.resume = function () {
  6753. this.paused = false;
  6754. this.controller.onNext(true);
  6755. };
  6756. return PausableBufferedObservable;
  6757. }(Observable));
  6758. /**
  6759. * Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
  6760. * and yields the values that were buffered while paused.
  6761. * @example
  6762. * var pauser = new Rx.Subject();
  6763. * var source = Rx.Observable.interval(100).pausableBuffered(pauser);
  6764. * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
  6765. * @returns {Observable} The observable sequence which is paused based upon the pauser.
  6766. */
  6767. observableProto.pausableBuffered = function (pauser) {
  6768. return new PausableBufferedObservable(this, pauser);
  6769. };
  6770. var ControlledObservable = (function (__super__) {
  6771. inherits(ControlledObservable, __super__);
  6772. function ControlledObservable (source, enableQueue, scheduler) {
  6773. __super__.call(this);
  6774. this.subject = new ControlledSubject(enableQueue, scheduler);
  6775. this.source = source.multicast(this.subject).refCount();
  6776. }
  6777. ControlledObservable.prototype._subscribe = function (o) {
  6778. return this.source.subscribe(o);
  6779. };
  6780. ControlledObservable.prototype.request = function (numberOfItems) {
  6781. return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
  6782. };
  6783. return ControlledObservable;
  6784. }(Observable));
  6785. var ControlledSubject = (function (__super__) {
  6786. inherits(ControlledSubject, __super__);
  6787. function ControlledSubject(enableQueue, scheduler) {
  6788. enableQueue == null && (enableQueue = true);
  6789. __super__.call(this);
  6790. this.subject = new Subject();
  6791. this.enableQueue = enableQueue;
  6792. this.queue = enableQueue ? [] : null;
  6793. this.requestedCount = 0;
  6794. this.requestedDisposable = null;
  6795. this.error = null;
  6796. this.hasFailed = false;
  6797. this.hasCompleted = false;
  6798. this.scheduler = scheduler || currentThreadScheduler;
  6799. }
  6800. addProperties(ControlledSubject.prototype, Observer, {
  6801. _subscribe: function (o) {
  6802. return this.subject.subscribe(o);
  6803. },
  6804. onCompleted: function () {
  6805. this.hasCompleted = true;
  6806. if (!this.enableQueue || this.queue.length === 0) {
  6807. this.subject.onCompleted();
  6808. this.disposeCurrentRequest();
  6809. } else {
  6810. this.queue.push(Notification.createOnCompleted());
  6811. }
  6812. },
  6813. onError: function (error) {
  6814. this.hasFailed = true;
  6815. this.error = error;
  6816. if (!this.enableQueue || this.queue.length === 0) {
  6817. this.subject.onError(error);
  6818. this.disposeCurrentRequest();
  6819. } else {
  6820. this.queue.push(Notification.createOnError(error));
  6821. }
  6822. },
  6823. onNext: function (value) {
  6824. if (this.requestedCount <= 0) {
  6825. this.enableQueue && this.queue.push(Notification.createOnNext(value));
  6826. } else {
  6827. (this.requestedCount-- === 0) && this.disposeCurrentRequest();
  6828. this.subject.onNext(value);
  6829. }
  6830. },
  6831. _processRequest: function (numberOfItems) {
  6832. if (this.enableQueue) {
  6833. while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) {
  6834. var first = this.queue.shift();
  6835. first.accept(this.subject);
  6836. if (first.kind === 'N') {
  6837. numberOfItems--;
  6838. } else {
  6839. this.disposeCurrentRequest();
  6840. this.queue = [];
  6841. }
  6842. }
  6843. }
  6844. return numberOfItems;
  6845. },
  6846. request: function (number) {
  6847. this.disposeCurrentRequest();
  6848. var self = this;
  6849. this.requestedDisposable = this.scheduler.schedule(number,
  6850. function(s, i) {
  6851. var remaining = self._processRequest(i);
  6852. var stopped = self.hasCompleted || self.hasFailed;
  6853. if (!stopped && remaining > 0) {
  6854. self.requestedCount = remaining;
  6855. return disposableCreate(function () {
  6856. self.requestedCount = 0;
  6857. });
  6858. // Scheduled item is still in progress. Return a new
  6859. // disposable to allow the request to be interrupted
  6860. // via dispose.
  6861. }
  6862. });
  6863. return this.requestedDisposable;
  6864. },
  6865. disposeCurrentRequest: function () {
  6866. if (this.requestedDisposable) {
  6867. this.requestedDisposable.dispose();
  6868. this.requestedDisposable = null;
  6869. }
  6870. }
  6871. });
  6872. return ControlledSubject;
  6873. }(Observable));
  6874. /**
  6875. * Attaches a controller to the observable sequence with the ability to queue.
  6876. * @example
  6877. * var source = Rx.Observable.interval(100).controlled();
  6878. * source.request(3); // Reads 3 values
  6879. * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request
  6880. * @param {Scheduler} scheduler determines how the requests will be scheduled
  6881. * @returns {Observable} The observable sequence which only propagates values on request.
  6882. */
  6883. observableProto.controlled = function (enableQueue, scheduler) {
  6884. if (enableQueue && isScheduler(enableQueue)) {
  6885. scheduler = enableQueue;
  6886. enableQueue = true;
  6887. }
  6888. if (enableQueue == null) { enableQueue = true; }
  6889. return new ControlledObservable(this, enableQueue, scheduler);
  6890. };
  6891. var StopAndWaitObservable = (function (__super__) {
  6892. inherits(StopAndWaitObservable, __super__);
  6893. function StopAndWaitObservable (source) {
  6894. __super__.call(this);
  6895. this.source = source;
  6896. }
  6897. function scheduleMethod(s, self) {
  6898. return self.source.request(1);
  6899. }
  6900. StopAndWaitObservable.prototype._subscribe = function (o) {
  6901. this.subscription = this.source.subscribe(new StopAndWaitObserver(o, this, this.subscription));
  6902. return new BinaryDisposable(
  6903. this.subscription,
  6904. defaultScheduler.schedule(this, scheduleMethod)
  6905. );
  6906. };
  6907. var StopAndWaitObserver = (function (__sub__) {
  6908. inherits(StopAndWaitObserver, __sub__);
  6909. function StopAndWaitObserver (observer, observable, cancel) {
  6910. __sub__.call(this);
  6911. this.observer = observer;
  6912. this.observable = observable;
  6913. this.cancel = cancel;
  6914. this.scheduleDisposable = null;
  6915. }
  6916. StopAndWaitObserver.prototype.completed = function () {
  6917. this.observer.onCompleted();
  6918. this.dispose();
  6919. };
  6920. StopAndWaitObserver.prototype.error = function (error) {
  6921. this.observer.onError(error);
  6922. this.dispose();
  6923. };
  6924. function innerScheduleMethod(s, self) {
  6925. return self.observable.source.request(1);
  6926. }
  6927. StopAndWaitObserver.prototype.next = function (value) {
  6928. this.observer.onNext(value);
  6929. this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod);
  6930. };
  6931. StopAndWaitObserver.dispose = function () {
  6932. this.observer = null;
  6933. if (this.cancel) {
  6934. this.cancel.dispose();
  6935. this.cancel = null;
  6936. }
  6937. if (this.scheduleDisposable) {
  6938. this.scheduleDisposable.dispose();
  6939. this.scheduleDisposable = null;
  6940. }
  6941. __sub__.prototype.dispose.call(this);
  6942. };
  6943. return StopAndWaitObserver;
  6944. }(AbstractObserver));
  6945. return StopAndWaitObservable;
  6946. }(Observable));
  6947. /**
  6948. * Attaches a stop and wait observable to the current observable.
  6949. * @returns {Observable} A stop and wait observable.
  6950. */
  6951. ControlledObservable.prototype.stopAndWait = function () {
  6952. return new StopAndWaitObservable(this);
  6953. };
  6954. var WindowedObservable = (function (__super__) {
  6955. inherits(WindowedObservable, __super__);
  6956. function WindowedObservable(source, windowSize) {
  6957. __super__.call(this);
  6958. this.source = source;
  6959. this.windowSize = windowSize;
  6960. }
  6961. function scheduleMethod(s, self) {
  6962. return self.source.request(self.windowSize);
  6963. }
  6964. WindowedObservable.prototype._subscribe = function (o) {
  6965. this.subscription = this.source.subscribe(new WindowedObserver(o, this, this.subscription));
  6966. return new BinaryDisposable(
  6967. this.subscription,
  6968. defaultScheduler.schedule(this, scheduleMethod)
  6969. );
  6970. };
  6971. var WindowedObserver = (function (__sub__) {
  6972. inherits(WindowedObserver, __sub__);
  6973. function WindowedObserver(observer, observable, cancel) {
  6974. this.observer = observer;
  6975. this.observable = observable;
  6976. this.cancel = cancel;
  6977. this.received = 0;
  6978. this.scheduleDisposable = null;
  6979. __sub__.call(this);
  6980. }
  6981. WindowedObserver.prototype.completed = function () {
  6982. this.observer.onCompleted();
  6983. this.dispose();
  6984. };
  6985. WindowedObserver.prototype.error = function (error) {
  6986. this.observer.onError(error);
  6987. this.dispose();
  6988. };
  6989. function innerScheduleMethod(s, self) {
  6990. return self.observable.source.request(self.observable.windowSize);
  6991. }
  6992. WindowedObserver.prototype.next = function (value) {
  6993. this.observer.onNext(value);
  6994. this.received = ++this.received % this.observable.windowSize;
  6995. this.received === 0 && (this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod));
  6996. };
  6997. WindowedObserver.prototype.dispose = function () {
  6998. this.observer = null;
  6999. if (this.cancel) {
  7000. this.cancel.dispose();
  7001. this.cancel = null;
  7002. }
  7003. if (this.scheduleDisposable) {
  7004. this.scheduleDisposable.dispose();
  7005. this.scheduleDisposable = null;
  7006. }
  7007. __sub__.prototype.dispose.call(this);
  7008. };
  7009. return WindowedObserver;
  7010. }(AbstractObserver));
  7011. return WindowedObservable;
  7012. }(Observable));
  7013. /**
  7014. * Creates a sliding windowed observable based upon the window size.
  7015. * @param {Number} windowSize The number of items in the window
  7016. * @returns {Observable} A windowed observable based upon the window size.
  7017. */
  7018. ControlledObservable.prototype.windowed = function (windowSize) {
  7019. return new WindowedObservable(this, windowSize);
  7020. };
  7021. /**
  7022. * Pipes the existing Observable sequence into a Node.js Stream.
  7023. * @param {Stream} dest The destination Node.js stream.
  7024. * @returns {Stream} The destination stream.
  7025. */
  7026. observableProto.pipe = function (dest) {
  7027. var source = this.pausableBuffered();
  7028. function onDrain() {
  7029. source.resume();
  7030. }
  7031. dest.addListener('drain', onDrain);
  7032. source.subscribe(
  7033. function (x) {
  7034. !dest.write(x) && source.pause();
  7035. },
  7036. function (err) {
  7037. dest.emit('error', err);
  7038. },
  7039. function () {
  7040. // Hack check because STDIO is not closable
  7041. !dest._isStdio && dest.end();
  7042. dest.removeListener('drain', onDrain);
  7043. });
  7044. source.resume();
  7045. return dest;
  7046. };
  7047. var MulticastObservable = (function (__super__) {
  7048. inherits(MulticastObservable, __super__);
  7049. function MulticastObservable(source, fn1, fn2) {
  7050. this.source = source;
  7051. this._fn1 = fn1;
  7052. this._fn2 = fn2;
  7053. __super__.call(this);
  7054. }
  7055. MulticastObservable.prototype.subscribeCore = function (o) {
  7056. var connectable = this.source.multicast(this._fn1());
  7057. return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());
  7058. };
  7059. return MulticastObservable;
  7060. }(ObservableBase));
  7061. /**
  7062. * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
  7063. * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
  7064. * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
  7065. *
  7066. * @example
  7067. * 1 - res = source.multicast(observable);
  7068. * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
  7069. *
  7070. * @param {Function|Subject} subjectOrSubjectSelector
  7071. * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
  7072. * Or:
  7073. * Subject to push source elements into.
  7074. *
  7075. * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
  7076. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  7077. */
  7078. observableProto.multicast = function (subjectOrSubjectSelector, selector) {
  7079. return isFunction(subjectOrSubjectSelector) ?
  7080. new MulticastObservable(this, subjectOrSubjectSelector, selector) :
  7081. new ConnectableObservable(this, subjectOrSubjectSelector);
  7082. };
  7083. /**
  7084. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
  7085. * This operator is a specialization of Multicast using a regular Subject.
  7086. *
  7087. * @example
  7088. * var resres = source.publish();
  7089. * var res = source.publish(function (x) { return x; });
  7090. *
  7091. * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
  7092. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  7093. */
  7094. observableProto.publish = function (selector) {
  7095. return selector && isFunction(selector) ?
  7096. this.multicast(function () { return new Subject(); }, selector) :
  7097. this.multicast(new Subject());
  7098. };
  7099. /**
  7100. * Returns an observable sequence that shares a single subscription to the underlying sequence.
  7101. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
  7102. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  7103. */
  7104. observableProto.share = function () {
  7105. return this.publish().refCount();
  7106. };
  7107. /**
  7108. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
  7109. * This operator is a specialization of Multicast using a AsyncSubject.
  7110. *
  7111. * @example
  7112. * var res = source.publishLast();
  7113. * var res = source.publishLast(function (x) { return x; });
  7114. *
  7115. * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
  7116. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  7117. */
  7118. observableProto.publishLast = function (selector) {
  7119. return selector && isFunction(selector) ?
  7120. this.multicast(function () { return new AsyncSubject(); }, selector) :
  7121. this.multicast(new AsyncSubject());
  7122. };
  7123. /**
  7124. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
  7125. * This operator is a specialization of Multicast using a BehaviorSubject.
  7126. *
  7127. * @example
  7128. * var res = source.publishValue(42);
  7129. * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
  7130. *
  7131. * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
  7132. * @param {Mixed} initialValue Initial value received by observers upon subscription.
  7133. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  7134. */
  7135. observableProto.publishValue = function (initialValueOrSelector, initialValue) {
  7136. return arguments.length === 2 ?
  7137. this.multicast(function () {
  7138. return new BehaviorSubject(initialValue);
  7139. }, initialValueOrSelector) :
  7140. this.multicast(new BehaviorSubject(initialValueOrSelector));
  7141. };
  7142. /**
  7143. * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
  7144. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
  7145. * @param {Mixed} initialValue Initial value received by observers upon subscription.
  7146. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  7147. */
  7148. observableProto.shareValue = function (initialValue) {
  7149. return this.publishValue(initialValue).refCount();
  7150. };
  7151. /**
  7152. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
  7153. * This operator is a specialization of Multicast using a ReplaySubject.
  7154. *
  7155. * @example
  7156. * var res = source.replay(null, 3);
  7157. * var res = source.replay(null, 3, 500);
  7158. * var res = source.replay(null, 3, 500, scheduler);
  7159. * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
  7160. *
  7161. * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
  7162. * @param bufferSize [Optional] Maximum element count of the replay buffer.
  7163. * @param windowSize [Optional] Maximum time length of the replay buffer.
  7164. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
  7165. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  7166. */
  7167. observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
  7168. return selector && isFunction(selector) ?
  7169. this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
  7170. this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
  7171. };
  7172. /**
  7173. * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
  7174. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
  7175. *
  7176. * @example
  7177. * var res = source.shareReplay(3);
  7178. * var res = source.shareReplay(3, 500);
  7179. * var res = source.shareReplay(3, 500, scheduler);
  7180. *
  7181. * @param bufferSize [Optional] Maximum element count of the replay buffer.
  7182. * @param window [Optional] Maximum time length of the replay buffer.
  7183. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
  7184. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  7185. */
  7186. observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
  7187. return this.replay(null, bufferSize, windowSize, scheduler).refCount();
  7188. };
  7189. var InnerSubscription = function (s, o) {
  7190. this._s = s;
  7191. this._o = o;
  7192. };
  7193. InnerSubscription.prototype.dispose = function () {
  7194. if (!this._s.isDisposed && this._o !== null) {
  7195. var idx = this._s.observers.indexOf(this._o);
  7196. this._s.observers.splice(idx, 1);
  7197. this._o = null;
  7198. }
  7199. };
  7200. var RefCountObservable = (function (__super__) {
  7201. inherits(RefCountObservable, __super__);
  7202. function RefCountObservable(source) {
  7203. this.source = source;
  7204. this._count = 0;
  7205. this._connectableSubscription = null;
  7206. __super__.call(this);
  7207. }
  7208. RefCountObservable.prototype.subscribeCore = function (o) {
  7209. var subscription = this.source.subscribe(o);
  7210. ++this._count === 1 && (this._connectableSubscription = this.source.connect());
  7211. return new RefCountDisposable(this, subscription);
  7212. };
  7213. function RefCountDisposable(p, s) {
  7214. this._p = p;
  7215. this._s = s;
  7216. this.isDisposed = false;
  7217. }
  7218. RefCountDisposable.prototype.dispose = function () {
  7219. if (!this.isDisposed) {
  7220. this.isDisposed = true;
  7221. this._s.dispose();
  7222. --this._p._count === 0 && this._p._connectableSubscription.dispose();
  7223. }
  7224. };
  7225. return RefCountObservable;
  7226. }(ObservableBase));
  7227. var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
  7228. inherits(ConnectableObservable, __super__);
  7229. function ConnectableObservable(source, subject) {
  7230. this.source = source;
  7231. this._connection = null;
  7232. this._source = source.asObservable();
  7233. this._subject = subject;
  7234. __super__.call(this);
  7235. }
  7236. function ConnectDisposable(parent, subscription) {
  7237. this._p = parent;
  7238. this._s = subscription;
  7239. }
  7240. ConnectDisposable.prototype.dispose = function () {
  7241. if (this._s) {
  7242. this._s.dispose();
  7243. this._s = null;
  7244. this._p._connection = null;
  7245. }
  7246. };
  7247. ConnectableObservable.prototype.connect = function () {
  7248. if (!this._connection) {
  7249. if (this._subject.isStopped) {
  7250. return disposableEmpty;
  7251. }
  7252. var subscription = this._source.subscribe(this._subject);
  7253. this._connection = new ConnectDisposable(this, subscription);
  7254. }
  7255. return this._connection;
  7256. };
  7257. ConnectableObservable.prototype._subscribe = function (o) {
  7258. return this._subject.subscribe(o);
  7259. };
  7260. ConnectableObservable.prototype.refCount = function () {
  7261. return new RefCountObservable(this);
  7262. };
  7263. return ConnectableObservable;
  7264. }(Observable));
  7265. /**
  7266. * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
  7267. * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
  7268. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
  7269. */
  7270. observableProto.singleInstance = function() {
  7271. var source = this, hasObservable = false, observable;
  7272. function getObservable() {
  7273. if (!hasObservable) {
  7274. hasObservable = true;
  7275. observable = source['finally'](function() { hasObservable = false; }).publish().refCount();
  7276. }
  7277. return observable;
  7278. }
  7279. return new AnonymousObservable(function(o) {
  7280. return getObservable().subscribe(o);
  7281. });
  7282. };
  7283. /**
  7284. * Correlates the elements of two sequences based on overlapping durations.
  7285. *
  7286. * @param {Observable} right The right observable sequence to join elements for.
  7287. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
  7288. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
  7289. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
  7290. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
  7291. */
  7292. observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
  7293. var left = this;
  7294. return new AnonymousObservable(function (o) {
  7295. var group = new CompositeDisposable();
  7296. var leftDone = false, rightDone = false;
  7297. var leftId = 0, rightId = 0;
  7298. var leftMap = new Map(), rightMap = new Map();
  7299. var handleError = function (e) { o.onError(e); };
  7300. group.add(left.subscribe(
  7301. function (value) {
  7302. var id = leftId++, md = new SingleAssignmentDisposable();
  7303. leftMap.set(id, value);
  7304. group.add(md);
  7305. var duration = tryCatch(leftDurationSelector)(value);
  7306. if (duration === errorObj) { return o.onError(duration.e); }
  7307. md.setDisposable(duration.take(1).subscribe(
  7308. noop,
  7309. handleError,
  7310. function () {
  7311. leftMap['delete'](id) && leftMap.size === 0 && leftDone && o.onCompleted();
  7312. group.remove(md);
  7313. }));
  7314. rightMap.forEach(function (v) {
  7315. var result = tryCatch(resultSelector)(value, v);
  7316. if (result === errorObj) { return o.onError(result.e); }
  7317. o.onNext(result);
  7318. });
  7319. },
  7320. handleError,
  7321. function () {
  7322. leftDone = true;
  7323. (rightDone || leftMap.size === 0) && o.onCompleted();
  7324. })
  7325. );
  7326. group.add(right.subscribe(
  7327. function (value) {
  7328. var id = rightId++, md = new SingleAssignmentDisposable();
  7329. rightMap.set(id, value);
  7330. group.add(md);
  7331. var duration = tryCatch(rightDurationSelector)(value);
  7332. if (duration === errorObj) { return o.onError(duration.e); }
  7333. md.setDisposable(duration.take(1).subscribe(
  7334. noop,
  7335. handleError,
  7336. function () {
  7337. rightMap['delete'](id) && rightMap.size === 0 && rightDone && o.onCompleted();
  7338. group.remove(md);
  7339. }));
  7340. leftMap.forEach(function (v) {
  7341. var result = tryCatch(resultSelector)(v, value);
  7342. if (result === errorObj) { return o.onError(result.e); }
  7343. o.onNext(result);
  7344. });
  7345. },
  7346. handleError,
  7347. function () {
  7348. rightDone = true;
  7349. (leftDone || rightMap.size === 0) && o.onCompleted();
  7350. })
  7351. );
  7352. return group;
  7353. }, left);
  7354. };
  7355. /**
  7356. * Correlates the elements of two sequences based on overlapping durations, and groups the results.
  7357. *
  7358. * @param {Observable} right The right observable sequence to join elements for.
  7359. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
  7360. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
  7361. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
  7362. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
  7363. */
  7364. observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
  7365. var left = this;
  7366. return new AnonymousObservable(function (o) {
  7367. var group = new CompositeDisposable();
  7368. var r = new RefCountDisposable(group);
  7369. var leftMap = new Map(), rightMap = new Map();
  7370. var leftId = 0, rightId = 0;
  7371. var handleError = function (e) { return function (v) { v.onError(e); }; };
  7372. function handleError(e) { };
  7373. group.add(left.subscribe(
  7374. function (value) {
  7375. var s = new Subject();
  7376. var id = leftId++;
  7377. leftMap.set(id, s);
  7378. var result = tryCatch(resultSelector)(value, addRef(s, r));
  7379. if (result === errorObj) {
  7380. leftMap.forEach(handleError(result.e));
  7381. return o.onError(result.e);
  7382. }
  7383. o.onNext(result);
  7384. rightMap.forEach(function (v) { s.onNext(v); });
  7385. var md = new SingleAssignmentDisposable();
  7386. group.add(md);
  7387. var duration = tryCatch(leftDurationSelector)(value);
  7388. if (duration === errorObj) {
  7389. leftMap.forEach(handleError(duration.e));
  7390. return o.onError(duration.e);
  7391. }
  7392. md.setDisposable(duration.take(1).subscribe(
  7393. noop,
  7394. function (e) {
  7395. leftMap.forEach(handleError(e));
  7396. o.onError(e);
  7397. },
  7398. function () {
  7399. leftMap['delete'](id) && s.onCompleted();
  7400. group.remove(md);
  7401. }));
  7402. },
  7403. function (e) {
  7404. leftMap.forEach(handleError(e));
  7405. o.onError(e);
  7406. },
  7407. function () { o.onCompleted(); })
  7408. );
  7409. group.add(right.subscribe(
  7410. function (value) {
  7411. var id = rightId++;
  7412. rightMap.set(id, value);
  7413. var md = new SingleAssignmentDisposable();
  7414. group.add(md);
  7415. var duration = tryCatch(rightDurationSelector)(value);
  7416. if (duration === errorObj) {
  7417. leftMap.forEach(handleError(duration.e));
  7418. return o.onError(duration.e);
  7419. }
  7420. md.setDisposable(duration.take(1).subscribe(
  7421. noop,
  7422. function (e) {
  7423. leftMap.forEach(handleError(e));
  7424. o.onError(e);
  7425. },
  7426. function () {
  7427. rightMap['delete'](id);
  7428. group.remove(md);
  7429. }));
  7430. leftMap.forEach(function (v) { v.onNext(value); });
  7431. },
  7432. function (e) {
  7433. leftMap.forEach(handleError(e));
  7434. o.onError(e);
  7435. })
  7436. );
  7437. return r;
  7438. }, left);
  7439. };
  7440. function toArray(x) { return x.toArray(); }
  7441. /**
  7442. * Projects each element of an observable sequence into zero or more buffers.
  7443. * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
  7444. * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
  7445. * @returns {Observable} An observable sequence of windows.
  7446. */
  7447. observableProto.buffer = function () {
  7448. return this.window.apply(this, arguments)
  7449. .flatMap(toArray);
  7450. };
  7451. /**
  7452. * Projects each element of an observable sequence into zero or more windows.
  7453. *
  7454. * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
  7455. * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
  7456. * @returns {Observable} An observable sequence of windows.
  7457. */
  7458. observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
  7459. if (arguments.length === 1 && typeof arguments[0] !== 'function') {
  7460. return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
  7461. }
  7462. return typeof windowOpeningsOrClosingSelector === 'function' ?
  7463. observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
  7464. observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
  7465. };
  7466. function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
  7467. return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
  7468. return win;
  7469. });
  7470. }
  7471. function observableWindowWithBoundaries(windowBoundaries) {
  7472. var source = this;
  7473. return new AnonymousObservable(function (observer) {
  7474. var win = new Subject(),
  7475. d = new CompositeDisposable(),
  7476. r = new RefCountDisposable(d);
  7477. observer.onNext(addRef(win, r));
  7478. d.add(source.subscribe(function (x) {
  7479. win.onNext(x);
  7480. }, function (err) {
  7481. win.onError(err);
  7482. observer.onError(err);
  7483. }, function () {
  7484. win.onCompleted();
  7485. observer.onCompleted();
  7486. }));
  7487. isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
  7488. d.add(windowBoundaries.subscribe(function (w) {
  7489. win.onCompleted();
  7490. win = new Subject();
  7491. observer.onNext(addRef(win, r));
  7492. }, function (err) {
  7493. win.onError(err);
  7494. observer.onError(err);
  7495. }, function () {
  7496. win.onCompleted();
  7497. observer.onCompleted();
  7498. }));
  7499. return r;
  7500. }, source);
  7501. }
  7502. function observableWindowWithClosingSelector(windowClosingSelector) {
  7503. var source = this;
  7504. return new AnonymousObservable(function (observer) {
  7505. var m = new SerialDisposable(),
  7506. d = new CompositeDisposable(m),
  7507. r = new RefCountDisposable(d),
  7508. win = new Subject();
  7509. observer.onNext(addRef(win, r));
  7510. d.add(source.subscribe(function (x) {
  7511. win.onNext(x);
  7512. }, function (err) {
  7513. win.onError(err);
  7514. observer.onError(err);
  7515. }, function () {
  7516. win.onCompleted();
  7517. observer.onCompleted();
  7518. }));
  7519. function createWindowClose () {
  7520. var windowClose;
  7521. try {
  7522. windowClose = windowClosingSelector();
  7523. } catch (e) {
  7524. observer.onError(e);
  7525. return;
  7526. }
  7527. isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
  7528. var m1 = new SingleAssignmentDisposable();
  7529. m.setDisposable(m1);
  7530. m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
  7531. win.onError(err);
  7532. observer.onError(err);
  7533. }, function () {
  7534. win.onCompleted();
  7535. win = new Subject();
  7536. observer.onNext(addRef(win, r));
  7537. createWindowClose();
  7538. }));
  7539. }
  7540. createWindowClose();
  7541. return r;
  7542. }, source);
  7543. }
  7544. var PairwiseObservable = (function (__super__) {
  7545. inherits(PairwiseObservable, __super__);
  7546. function PairwiseObservable(source) {
  7547. this.source = source;
  7548. __super__.call(this);
  7549. }
  7550. PairwiseObservable.prototype.subscribeCore = function (o) {
  7551. return this.source.subscribe(new PairwiseObserver(o));
  7552. };
  7553. return PairwiseObservable;
  7554. }(ObservableBase));
  7555. var PairwiseObserver = (function(__super__) {
  7556. inherits(PairwiseObserver, __super__);
  7557. function PairwiseObserver(o) {
  7558. this._o = o;
  7559. this._p = null;
  7560. this._hp = false;
  7561. __super__.call(this);
  7562. }
  7563. PairwiseObserver.prototype.next = function (x) {
  7564. if (this._hp) {
  7565. this._o.onNext([this._p, x]);
  7566. } else {
  7567. this._hp = true;
  7568. }
  7569. this._p = x;
  7570. };
  7571. PairwiseObserver.prototype.error = function (err) { this._o.onError(err); };
  7572. PairwiseObserver.prototype.completed = function () { this._o.onCompleted(); };
  7573. return PairwiseObserver;
  7574. }(AbstractObserver));
  7575. /**
  7576. * Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
  7577. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
  7578. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
  7579. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
  7580. */
  7581. observableProto.pairwise = function () {
  7582. return new PairwiseObservable(this);
  7583. };
  7584. /**
  7585. * Returns two observables which partition the observations of the source by the given function.
  7586. * The first will trigger observations for those values for which the predicate returns true.
  7587. * The second will trigger observations for those values where the predicate returns false.
  7588. * The predicate is executed once for each subscribed observer.
  7589. * Both also propagate all error observations arising from the source and each completes
  7590. * when the source completes.
  7591. * @param {Function} predicate
  7592. * The function to determine which output Observable will trigger a particular observation.
  7593. * @returns {Array}
  7594. * An array of observables. The first triggers when the predicate returns true,
  7595. * and the second triggers when the predicate returns false.
  7596. */
  7597. observableProto.partition = function(predicate, thisArg) {
  7598. var fn = bindCallback(predicate, thisArg, 3);
  7599. return [
  7600. this.filter(predicate, thisArg),
  7601. this.filter(function (x, i, o) { return !fn(x, i, o); })
  7602. ];
  7603. };
  7604. var WhileEnumerable = (function(__super__) {
  7605. inherits(WhileEnumerable, __super__);
  7606. function WhileEnumerable(c, s) {
  7607. this.c = c;
  7608. this.s = s;
  7609. }
  7610. WhileEnumerable.prototype[$iterator$] = function () {
  7611. var self = this;
  7612. return {
  7613. next: function () {
  7614. return self.c() ?
  7615. { done: false, value: self.s } :
  7616. { done: true, value: void 0 };
  7617. }
  7618. };
  7619. };
  7620. return WhileEnumerable;
  7621. }(Enumerable));
  7622. function enumerableWhile(condition, source) {
  7623. return new WhileEnumerable(condition, source);
  7624. }
  7625. /**
  7626. * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
  7627. * This operator allows for a fluent style of writing queries that use the same sequence multiple times.
  7628. *
  7629. * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
  7630. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  7631. */
  7632. observableProto.letBind = observableProto['let'] = function (func) {
  7633. return func(this);
  7634. };
  7635. /**
  7636. * Determines whether an observable collection contains values.
  7637. *
  7638. * @example
  7639. * 1 - res = Rx.Observable.if(condition, obs1);
  7640. * 2 - res = Rx.Observable.if(condition, obs1, obs2);
  7641. * 3 - res = Rx.Observable.if(condition, obs1, scheduler);
  7642. * @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
  7643. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
  7644. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
  7645. * @returns {Observable} An observable sequence which is either the thenSource or elseSource.
  7646. */
  7647. Observable['if'] = function (condition, thenSource, elseSourceOrScheduler) {
  7648. return observableDefer(function () {
  7649. elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
  7650. isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
  7651. isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
  7652. // Assume a scheduler for empty only
  7653. typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
  7654. return condition() ? thenSource : elseSourceOrScheduler;
  7655. });
  7656. };
  7657. /**
  7658. * Concatenates the observable sequences obtained by running the specified result selector for each element in source.
  7659. * There is an alias for this method called 'forIn' for browsers <IE9
  7660. * @param {Array} sources An array of values to turn into an observable sequence.
  7661. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
  7662. * @returns {Observable} An observable sequence from the concatenated observable sequences.
  7663. */
  7664. Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
  7665. return enumerableOf(sources, resultSelector, thisArg).concat();
  7666. };
  7667. /**
  7668. * Repeats source as long as condition holds emulating a while loop.
  7669. * There is an alias for this method called 'whileDo' for browsers <IE9
  7670. *
  7671. * @param {Function} condition The condition which determines if the source will be repeated.
  7672. * @param {Observable} source The observable sequence that will be run if the condition function returns true.
  7673. * @returns {Observable} An observable sequence which is repeated as long as the condition holds.
  7674. */
  7675. var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
  7676. isPromise(source) && (source = observableFromPromise(source));
  7677. return enumerableWhile(condition, source).concat();
  7678. };
  7679. /**
  7680. * Repeats source as long as condition holds emulating a do while loop.
  7681. *
  7682. * @param {Function} condition The condition which determines if the source will be repeated.
  7683. * @param {Observable} source The observable sequence that will be run if the condition function returns true.
  7684. * @returns {Observable} An observable sequence which is repeated as long as the condition holds.
  7685. */
  7686. observableProto.doWhile = function (condition) {
  7687. return observableConcat([this, observableWhileDo(condition, this)]);
  7688. };
  7689. /**
  7690. * Uses selector to determine which source in sources to use.
  7691. * @param {Function} selector The function which extracts the value for to test in a case statement.
  7692. * @param {Array} sources A object which has keys which correspond to the case statement labels.
  7693. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
  7694. *
  7695. * @returns {Observable} An observable sequence which is determined by a case statement.
  7696. */
  7697. Observable['case'] = function (selector, sources, defaultSourceOrScheduler) {
  7698. return observableDefer(function () {
  7699. isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
  7700. defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
  7701. isScheduler(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
  7702. var result = sources[selector()];
  7703. isPromise(result) && (result = observableFromPromise(result));
  7704. return result || defaultSourceOrScheduler;
  7705. });
  7706. };
  7707. var ExpandObservable = (function(__super__) {
  7708. inherits(ExpandObservable, __super__);
  7709. function ExpandObservable(source, fn, scheduler) {
  7710. this.source = source;
  7711. this._fn = fn;
  7712. this._scheduler = scheduler;
  7713. __super__.call(this);
  7714. }
  7715. function scheduleRecursive(args, recurse) {
  7716. var state = args[0], self = args[1];
  7717. var work;
  7718. if (state.q.length > 0) {
  7719. work = state.q.shift();
  7720. } else {
  7721. state.isAcquired = false;
  7722. return;
  7723. }
  7724. var m1 = new SingleAssignmentDisposable();
  7725. state.d.add(m1);
  7726. m1.setDisposable(work.subscribe(new ExpandObserver(state, self, m1)));
  7727. recurse([state, self]);
  7728. }
  7729. ExpandObservable.prototype._ensureActive = function (state) {
  7730. var isOwner = false;
  7731. if (state.q.length > 0) {
  7732. isOwner = !state.isAcquired;
  7733. state.isAcquired = true;
  7734. }
  7735. isOwner && state.m.setDisposable(this._scheduler.scheduleRecursive([state, this], scheduleRecursive));
  7736. };
  7737. ExpandObservable.prototype.subscribeCore = function (o) {
  7738. var m = new SerialDisposable(),
  7739. d = new CompositeDisposable(m),
  7740. state = {
  7741. q: [],
  7742. m: m,
  7743. d: d,
  7744. activeCount: 0,
  7745. isAcquired: false,
  7746. o: o
  7747. };
  7748. state.q.push(this.source);
  7749. state.activeCount++;
  7750. this._ensureActive(state);
  7751. return d;
  7752. };
  7753. return ExpandObservable;
  7754. }(ObservableBase));
  7755. var ExpandObserver = (function(__super__) {
  7756. inherits(ExpandObserver, __super__);
  7757. function ExpandObserver(state, parent, m1) {
  7758. this._s = state;
  7759. this._p = parent;
  7760. this._m1 = m1;
  7761. __super__.call(this);
  7762. }
  7763. ExpandObserver.prototype.next = function (x) {
  7764. this._s.o.onNext(x);
  7765. var result = tryCatch(this._p._fn)(x);
  7766. if (result === errorObj) { return this._s.o.onError(result.e); }
  7767. this._s.q.push(result);
  7768. this._s.activeCount++;
  7769. this._p._ensureActive(this._s);
  7770. };
  7771. ExpandObserver.prototype.error = function (e) {
  7772. this._s.o.onError(e);
  7773. };
  7774. ExpandObserver.prototype.completed = function () {
  7775. this._s.d.remove(this._m1);
  7776. this._s.activeCount--;
  7777. this._s.activeCount === 0 && this._s.o.onCompleted();
  7778. };
  7779. return ExpandObserver;
  7780. }(AbstractObserver));
  7781. /**
  7782. * Expands an observable sequence by recursively invoking selector.
  7783. *
  7784. * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
  7785. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
  7786. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
  7787. */
  7788. observableProto.expand = function (selector, scheduler) {
  7789. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  7790. return new ExpandObservable(this, selector, scheduler);
  7791. };
  7792. function argumentsToArray() {
  7793. var len = arguments.length, args = new Array(len);
  7794. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  7795. return args;
  7796. }
  7797. var ForkJoinObservable = (function (__super__) {
  7798. inherits(ForkJoinObservable, __super__);
  7799. function ForkJoinObservable(sources, cb) {
  7800. this._sources = sources;
  7801. this._cb = cb;
  7802. __super__.call(this);
  7803. }
  7804. ForkJoinObservable.prototype.subscribeCore = function (o) {
  7805. if (this._sources.length === 0) {
  7806. o.onCompleted();
  7807. return disposableEmpty;
  7808. }
  7809. var count = this._sources.length;
  7810. var state = {
  7811. finished: false,
  7812. hasResults: new Array(count),
  7813. hasCompleted: new Array(count),
  7814. results: new Array(count)
  7815. };
  7816. var subscriptions = new CompositeDisposable();
  7817. for (var i = 0, len = this._sources.length; i < len; i++) {
  7818. var source = this._sources[i];
  7819. isPromise(source) && (source = observableFromPromise(source));
  7820. subscriptions.add(source.subscribe(new ForkJoinObserver(o, state, i, this._cb, subscriptions)));
  7821. }
  7822. return subscriptions;
  7823. };
  7824. return ForkJoinObservable;
  7825. }(ObservableBase));
  7826. var ForkJoinObserver = (function(__super__) {
  7827. inherits(ForkJoinObserver, __super__);
  7828. function ForkJoinObserver(o, s, i, cb, subs) {
  7829. this._o = o;
  7830. this._s = s;
  7831. this._i = i;
  7832. this._cb = cb;
  7833. this._subs = subs;
  7834. __super__.call(this);
  7835. }
  7836. ForkJoinObserver.prototype.next = function (x) {
  7837. if (!this._s.finished) {
  7838. this._s.hasResults[this._i] = true;
  7839. this._s.results[this._i] = x;
  7840. }
  7841. };
  7842. ForkJoinObserver.prototype.error = function (e) {
  7843. this._s.finished = true;
  7844. this._o.onError(e);
  7845. this._subs.dispose();
  7846. };
  7847. ForkJoinObserver.prototype.completed = function () {
  7848. if (!this._s.finished) {
  7849. if (!this._s.hasResults[this._i]) {
  7850. return this._o.onCompleted();
  7851. }
  7852. this._s.hasCompleted[this._i] = true;
  7853. for (var i = 0; i < this._s.results.length; i++) {
  7854. if (!this._s.hasCompleted[i]) { return; }
  7855. }
  7856. this._s.finished = true;
  7857. var res = tryCatch(this._cb).apply(null, this._s.results);
  7858. if (res === errorObj) { return this._o.onError(res.e); }
  7859. this._o.onNext(res);
  7860. this._o.onCompleted();
  7861. }
  7862. };
  7863. return ForkJoinObserver;
  7864. }(AbstractObserver));
  7865. /**
  7866. * Runs all observable sequences in parallel and collect their last elements.
  7867. *
  7868. * @example
  7869. * 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
  7870. * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
  7871. * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
  7872. */
  7873. Observable.forkJoin = function () {
  7874. var len = arguments.length, args = new Array(len);
  7875. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  7876. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  7877. Array.isArray(args[0]) && (args = args[0]);
  7878. return new ForkJoinObservable(args, resultSelector);
  7879. };
  7880. /**
  7881. * Runs two observable sequences in parallel and combines their last elemenets.
  7882. * @param {Observable} second Second observable sequence.
  7883. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
  7884. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
  7885. */
  7886. observableProto.forkJoin = function () {
  7887. var len = arguments.length, args = new Array(len);
  7888. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  7889. if (Array.isArray(args[0])) {
  7890. args[0].unshift(this);
  7891. } else {
  7892. args.unshift(this);
  7893. }
  7894. return Observable.forkJoin.apply(null, args);
  7895. };
  7896. /**
  7897. * Comonadic bind operator.
  7898. * @param {Function} selector A transform function to apply to each element.
  7899. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
  7900. * @returns {Observable} An observable sequence which results from the comonadic bind operation.
  7901. */
  7902. observableProto.manySelect = observableProto.extend = function (selector, scheduler) {
  7903. isScheduler(scheduler) || (scheduler = Rx.Scheduler.immediate);
  7904. var source = this;
  7905. return observableDefer(function () {
  7906. var chain;
  7907. return source
  7908. .map(function (x) {
  7909. var curr = new ChainObservable(x);
  7910. chain && chain.onNext(x);
  7911. chain = curr;
  7912. return curr;
  7913. })
  7914. .tap(
  7915. noop,
  7916. function (e) { chain && chain.onError(e); },
  7917. function () { chain && chain.onCompleted(); }
  7918. )
  7919. .observeOn(scheduler)
  7920. .map(selector);
  7921. }, source);
  7922. };
  7923. var ChainObservable = (function (__super__) {
  7924. inherits(ChainObservable, __super__);
  7925. function ChainObservable(head) {
  7926. __super__.call(this);
  7927. this.head = head;
  7928. this.tail = new AsyncSubject();
  7929. }
  7930. addProperties(ChainObservable.prototype, Observer, {
  7931. _subscribe: function (o) {
  7932. var g = new CompositeDisposable();
  7933. g.add(currentThreadScheduler.schedule(this, function (_, self) {
  7934. o.onNext(self.head);
  7935. g.add(self.tail.mergeAll().subscribe(o));
  7936. }));
  7937. return g;
  7938. },
  7939. onCompleted: function () {
  7940. this.onNext(Observable.empty());
  7941. },
  7942. onError: function (e) {
  7943. this.onNext(Observable['throw'](e));
  7944. },
  7945. onNext: function (v) {
  7946. this.tail.onNext(v);
  7947. this.tail.onCompleted();
  7948. }
  7949. });
  7950. return ChainObservable;
  7951. }(Observable));
  7952. var Map = root.Map || (function () {
  7953. function Map() {
  7954. this.size = 0;
  7955. this._values = [];
  7956. this._keys = [];
  7957. }
  7958. Map.prototype['delete'] = function (key) {
  7959. var i = this._keys.indexOf(key);
  7960. if (i === -1) { return false; }
  7961. this._values.splice(i, 1);
  7962. this._keys.splice(i, 1);
  7963. this.size--;
  7964. return true;
  7965. };
  7966. Map.prototype.get = function (key) {
  7967. var i = this._keys.indexOf(key);
  7968. return i === -1 ? undefined : this._values[i];
  7969. };
  7970. Map.prototype.set = function (key, value) {
  7971. var i = this._keys.indexOf(key);
  7972. if (i === -1) {
  7973. this._keys.push(key);
  7974. this._values.push(value);
  7975. this.size++;
  7976. } else {
  7977. this._values[i] = value;
  7978. }
  7979. return this;
  7980. };
  7981. Map.prototype.forEach = function (cb, thisArg) {
  7982. for (var i = 0; i < this.size; i++) {
  7983. cb.call(thisArg, this._values[i], this._keys[i]);
  7984. }
  7985. };
  7986. return Map;
  7987. }());
  7988. /**
  7989. * @constructor
  7990. * Represents a join pattern over observable sequences.
  7991. */
  7992. function Pattern(patterns) {
  7993. this.patterns = patterns;
  7994. }
  7995. /**
  7996. * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
  7997. * @param other Observable sequence to match in addition to the current pattern.
  7998. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
  7999. */
  8000. Pattern.prototype.and = function (other) {
  8001. return new Pattern(this.patterns.concat(other));
  8002. };
  8003. /**
  8004. * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
  8005. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
  8006. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
  8007. */
  8008. Pattern.prototype.thenDo = function (selector) {
  8009. return new Plan(this, selector);
  8010. };
  8011. function Plan(expression, selector) {
  8012. this.expression = expression;
  8013. this.selector = selector;
  8014. }
  8015. function handleOnError(o) { return function (e) { o.onError(e); }; }
  8016. function handleOnNext(self, observer) {
  8017. return function onNext () {
  8018. var result = tryCatch(self.selector).apply(self, arguments);
  8019. if (result === errorObj) { return observer.onError(result.e); }
  8020. observer.onNext(result);
  8021. };
  8022. }
  8023. Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
  8024. var joinObservers = [], errHandler = handleOnError(observer);
  8025. for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
  8026. joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], errHandler));
  8027. }
  8028. var activePlan = new ActivePlan(joinObservers, handleOnNext(this, observer), function () {
  8029. for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
  8030. joinObservers[j].removeActivePlan(activePlan);
  8031. }
  8032. deactivate(activePlan);
  8033. });
  8034. for (i = 0, len = joinObservers.length; i < len; i++) {
  8035. joinObservers[i].addActivePlan(activePlan);
  8036. }
  8037. return activePlan;
  8038. };
  8039. function planCreateObserver(externalSubscriptions, observable, onError) {
  8040. var entry = externalSubscriptions.get(observable);
  8041. if (!entry) {
  8042. var observer = new JoinObserver(observable, onError);
  8043. externalSubscriptions.set(observable, observer);
  8044. return observer;
  8045. }
  8046. return entry;
  8047. }
  8048. function ActivePlan(joinObserverArray, onNext, onCompleted) {
  8049. this.joinObserverArray = joinObserverArray;
  8050. this.onNext = onNext;
  8051. this.onCompleted = onCompleted;
  8052. this.joinObservers = new Map();
  8053. for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
  8054. var joinObserver = this.joinObserverArray[i];
  8055. this.joinObservers.set(joinObserver, joinObserver);
  8056. }
  8057. }
  8058. ActivePlan.prototype.dequeue = function () {
  8059. this.joinObservers.forEach(function (v) { v.queue.shift(); });
  8060. };
  8061. ActivePlan.prototype.match = function () {
  8062. var i, len, hasValues = true;
  8063. for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
  8064. if (this.joinObserverArray[i].queue.length === 0) {
  8065. hasValues = false;
  8066. break;
  8067. }
  8068. }
  8069. if (hasValues) {
  8070. var firstValues = [],
  8071. isCompleted = false;
  8072. for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
  8073. firstValues.push(this.joinObserverArray[i].queue[0]);
  8074. this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
  8075. }
  8076. if (isCompleted) {
  8077. this.onCompleted();
  8078. } else {
  8079. this.dequeue();
  8080. var values = [];
  8081. for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
  8082. values.push(firstValues[i].value);
  8083. }
  8084. this.onNext.apply(this, values);
  8085. }
  8086. }
  8087. };
  8088. var JoinObserver = (function (__super__) {
  8089. inherits(JoinObserver, __super__);
  8090. function JoinObserver(source, onError) {
  8091. __super__.call(this);
  8092. this.source = source;
  8093. this.onError = onError;
  8094. this.queue = [];
  8095. this.activePlans = [];
  8096. this.subscription = new SingleAssignmentDisposable();
  8097. this.isDisposed = false;
  8098. }
  8099. var JoinObserverPrototype = JoinObserver.prototype;
  8100. JoinObserverPrototype.next = function (notification) {
  8101. if (!this.isDisposed) {
  8102. if (notification.kind === 'E') {
  8103. return this.onError(notification.error);
  8104. }
  8105. this.queue.push(notification);
  8106. var activePlans = this.activePlans.slice(0);
  8107. for (var i = 0, len = activePlans.length; i < len; i++) {
  8108. activePlans[i].match();
  8109. }
  8110. }
  8111. };
  8112. JoinObserverPrototype.error = noop;
  8113. JoinObserverPrototype.completed = noop;
  8114. JoinObserverPrototype.addActivePlan = function (activePlan) {
  8115. this.activePlans.push(activePlan);
  8116. };
  8117. JoinObserverPrototype.subscribe = function () {
  8118. this.subscription.setDisposable(this.source.materialize().subscribe(this));
  8119. };
  8120. JoinObserverPrototype.removeActivePlan = function (activePlan) {
  8121. this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
  8122. this.activePlans.length === 0 && this.dispose();
  8123. };
  8124. JoinObserverPrototype.dispose = function () {
  8125. __super__.prototype.dispose.call(this);
  8126. if (!this.isDisposed) {
  8127. this.isDisposed = true;
  8128. this.subscription.dispose();
  8129. }
  8130. };
  8131. return JoinObserver;
  8132. } (AbstractObserver));
  8133. /**
  8134. * Creates a pattern that matches when both observable sequences have an available value.
  8135. *
  8136. * @param right Observable sequence to match with the current sequence.
  8137. * @return {Pattern} Pattern object that matches when both observable sequences have an available value.
  8138. */
  8139. observableProto.and = function (right) {
  8140. return new Pattern([this, right]);
  8141. };
  8142. /**
  8143. * Matches when the observable sequence has an available value and projects the value.
  8144. *
  8145. * @param {Function} selector Selector that will be invoked for values in the source sequence.
  8146. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
  8147. */
  8148. observableProto.thenDo = function (selector) {
  8149. return new Pattern([this]).thenDo(selector);
  8150. };
  8151. /**
  8152. * Joins together the results from several patterns.
  8153. *
  8154. * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
  8155. * @returns {Observable} Observable sequence with the results form matching several patterns.
  8156. */
  8157. Observable.when = function () {
  8158. var len = arguments.length, plans;
  8159. if (Array.isArray(arguments[0])) {
  8160. plans = arguments[0];
  8161. } else {
  8162. plans = new Array(len);
  8163. for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
  8164. }
  8165. return new AnonymousObservable(function (o) {
  8166. var activePlans = [],
  8167. externalSubscriptions = new Map();
  8168. var outObserver = observerCreate(
  8169. function (x) { o.onNext(x); },
  8170. function (err) {
  8171. externalSubscriptions.forEach(function (v) { v.onError(err); });
  8172. o.onError(err);
  8173. },
  8174. function (x) { o.onCompleted(); }
  8175. );
  8176. try {
  8177. for (var i = 0, len = plans.length; i < len; i++) {
  8178. activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
  8179. var idx = activePlans.indexOf(activePlan);
  8180. activePlans.splice(idx, 1);
  8181. activePlans.length === 0 && o.onCompleted();
  8182. }));
  8183. }
  8184. } catch (e) {
  8185. return observableThrow(e).subscribe(o);
  8186. }
  8187. var group = new CompositeDisposable();
  8188. externalSubscriptions.forEach(function (joinObserver) {
  8189. joinObserver.subscribe();
  8190. group.add(joinObserver);
  8191. });
  8192. return group;
  8193. });
  8194. };
  8195. var TimerObservable = (function(__super__) {
  8196. inherits(TimerObservable, __super__);
  8197. function TimerObservable(dt, s) {
  8198. this._dt = dt;
  8199. this._s = s;
  8200. __super__.call(this);
  8201. }
  8202. TimerObservable.prototype.subscribeCore = function (o) {
  8203. return this._s.scheduleFuture(o, this._dt, scheduleMethod);
  8204. };
  8205. function scheduleMethod(s, o) {
  8206. o.onNext(0);
  8207. o.onCompleted();
  8208. }
  8209. return TimerObservable;
  8210. }(ObservableBase));
  8211. function _observableTimer(dueTime, scheduler) {
  8212. return new TimerObservable(dueTime, scheduler);
  8213. }
  8214. function observableTimerDateAndPeriod(dueTime, period, scheduler) {
  8215. return new AnonymousObservable(function (observer) {
  8216. var d = dueTime, p = normalizeTime(period);
  8217. return scheduler.scheduleRecursiveFuture(0, d, function (count, self) {
  8218. if (p > 0) {
  8219. var now = scheduler.now();
  8220. d = new Date(d.getTime() + p);
  8221. d.getTime() <= now && (d = new Date(now + p));
  8222. }
  8223. observer.onNext(count);
  8224. self(count + 1, new Date(d));
  8225. });
  8226. });
  8227. }
  8228. function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
  8229. return dueTime === period ?
  8230. new AnonymousObservable(function (observer) {
  8231. return scheduler.schedulePeriodic(0, period, function (count) {
  8232. observer.onNext(count);
  8233. return count + 1;
  8234. });
  8235. }) :
  8236. observableDefer(function () {
  8237. return observableTimerDateAndPeriod(new Date(scheduler.now() + dueTime), period, scheduler);
  8238. });
  8239. }
  8240. /**
  8241. * Returns an observable sequence that produces a value after each period.
  8242. *
  8243. * @example
  8244. * 1 - res = Rx.Observable.interval(1000);
  8245. * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
  8246. *
  8247. * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
  8248. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
  8249. * @returns {Observable} An observable sequence that produces a value after each period.
  8250. */
  8251. var observableinterval = Observable.interval = function (period, scheduler) {
  8252. return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : defaultScheduler);
  8253. };
  8254. /**
  8255. * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
  8256. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
  8257. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
  8258. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
  8259. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
  8260. */
  8261. var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
  8262. var period;
  8263. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8264. if (periodOrScheduler != null && typeof periodOrScheduler === 'number') {
  8265. period = periodOrScheduler;
  8266. } else if (isScheduler(periodOrScheduler)) {
  8267. scheduler = periodOrScheduler;
  8268. }
  8269. if ((dueTime instanceof Date || typeof dueTime === 'number') && period === undefined) {
  8270. return _observableTimer(dueTime, scheduler);
  8271. }
  8272. if (dueTime instanceof Date && period !== undefined) {
  8273. return observableTimerDateAndPeriod(dueTime, periodOrScheduler, scheduler);
  8274. }
  8275. return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
  8276. };
  8277. function observableDelayRelative(source, dueTime, scheduler) {
  8278. return new AnonymousObservable(function (o) {
  8279. var active = false,
  8280. cancelable = new SerialDisposable(),
  8281. exception = null,
  8282. q = [],
  8283. running = false,
  8284. subscription;
  8285. subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
  8286. var d, shouldRun;
  8287. if (notification.value.kind === 'E') {
  8288. q = [];
  8289. q.push(notification);
  8290. exception = notification.value.error;
  8291. shouldRun = !running;
  8292. } else {
  8293. q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
  8294. shouldRun = !active;
  8295. active = true;
  8296. }
  8297. if (shouldRun) {
  8298. if (exception !== null) {
  8299. o.onError(exception);
  8300. } else {
  8301. d = new SingleAssignmentDisposable();
  8302. cancelable.setDisposable(d);
  8303. d.setDisposable(scheduler.scheduleRecursiveFuture(null, dueTime, function (_, self) {
  8304. var e, recurseDueTime, result, shouldRecurse;
  8305. if (exception !== null) {
  8306. return;
  8307. }
  8308. running = true;
  8309. do {
  8310. result = null;
  8311. if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
  8312. result = q.shift().value;
  8313. }
  8314. if (result !== null) {
  8315. result.accept(o);
  8316. }
  8317. } while (result !== null);
  8318. shouldRecurse = false;
  8319. recurseDueTime = 0;
  8320. if (q.length > 0) {
  8321. shouldRecurse = true;
  8322. recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
  8323. } else {
  8324. active = false;
  8325. }
  8326. e = exception;
  8327. running = false;
  8328. if (e !== null) {
  8329. o.onError(e);
  8330. } else if (shouldRecurse) {
  8331. self(null, recurseDueTime);
  8332. }
  8333. }));
  8334. }
  8335. }
  8336. });
  8337. return new BinaryDisposable(subscription, cancelable);
  8338. }, source);
  8339. }
  8340. function observableDelayAbsolute(source, dueTime, scheduler) {
  8341. return observableDefer(function () {
  8342. return observableDelayRelative(source, dueTime - scheduler.now(), scheduler);
  8343. });
  8344. }
  8345. function delayWithSelector(source, subscriptionDelay, delayDurationSelector) {
  8346. var subDelay, selector;
  8347. if (isFunction(subscriptionDelay)) {
  8348. selector = subscriptionDelay;
  8349. } else {
  8350. subDelay = subscriptionDelay;
  8351. selector = delayDurationSelector;
  8352. }
  8353. return new AnonymousObservable(function (o) {
  8354. var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable();
  8355. function start() {
  8356. subscription.setDisposable(source.subscribe(
  8357. function (x) {
  8358. var delay = tryCatch(selector)(x);
  8359. if (delay === errorObj) { return o.onError(delay.e); }
  8360. var d = new SingleAssignmentDisposable();
  8361. delays.add(d);
  8362. d.setDisposable(delay.subscribe(
  8363. function () {
  8364. o.onNext(x);
  8365. delays.remove(d);
  8366. done();
  8367. },
  8368. function (e) { o.onError(e); },
  8369. function () {
  8370. o.onNext(x);
  8371. delays.remove(d);
  8372. done();
  8373. }
  8374. ));
  8375. },
  8376. function (e) { o.onError(e); },
  8377. function () {
  8378. atEnd = true;
  8379. subscription.dispose();
  8380. done();
  8381. }
  8382. ));
  8383. }
  8384. function done () {
  8385. atEnd && delays.length === 0 && o.onCompleted();
  8386. }
  8387. if (!subDelay) {
  8388. start();
  8389. } else {
  8390. subscription.setDisposable(subDelay.subscribe(start, function (e) { o.onError(e); }, start));
  8391. }
  8392. return new BinaryDisposable(subscription, delays);
  8393. }, source);
  8394. }
  8395. /**
  8396. * Time shifts the observable sequence by dueTime.
  8397. * The relative time intervals between the values are preserved.
  8398. *
  8399. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
  8400. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
  8401. * @returns {Observable} Time-shifted sequence.
  8402. */
  8403. observableProto.delay = function () {
  8404. var firstArg = arguments[0];
  8405. if (typeof firstArg === 'number' || firstArg instanceof Date) {
  8406. var dueTime = firstArg, scheduler = arguments[1];
  8407. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8408. return dueTime instanceof Date ?
  8409. observableDelayAbsolute(this, dueTime, scheduler) :
  8410. observableDelayRelative(this, dueTime, scheduler);
  8411. } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
  8412. return delayWithSelector(this, firstArg, arguments[1]);
  8413. } else {
  8414. throw new Error('Invalid arguments');
  8415. }
  8416. };
  8417. var DebounceObservable = (function (__super__) {
  8418. inherits(DebounceObservable, __super__);
  8419. function DebounceObservable(source, dt, s) {
  8420. isScheduler(s) || (s = defaultScheduler);
  8421. this.source = source;
  8422. this._dt = dt;
  8423. this._s = s;
  8424. __super__.call(this);
  8425. }
  8426. DebounceObservable.prototype.subscribeCore = function (o) {
  8427. var cancelable = new SerialDisposable();
  8428. return new BinaryDisposable(
  8429. this.source.subscribe(new DebounceObserver(o, this._dt, this._s, cancelable)),
  8430. cancelable);
  8431. };
  8432. return DebounceObservable;
  8433. }(ObservableBase));
  8434. var DebounceObserver = (function (__super__) {
  8435. inherits(DebounceObserver, __super__);
  8436. function DebounceObserver(observer, dueTime, scheduler, cancelable) {
  8437. this._o = observer;
  8438. this._d = dueTime;
  8439. this._scheduler = scheduler;
  8440. this._c = cancelable;
  8441. this._v = null;
  8442. this._hv = false;
  8443. this._id = 0;
  8444. __super__.call(this);
  8445. }
  8446. function scheduleFuture(s, state) {
  8447. state.self._hv && state.self._id === state.currentId && state.self._o.onNext(state.x);
  8448. state.self._hv = false;
  8449. }
  8450. DebounceObserver.prototype.next = function (x) {
  8451. this._hv = true;
  8452. this._v = x;
  8453. var currentId = ++this._id, d = new SingleAssignmentDisposable();
  8454. this._c.setDisposable(d);
  8455. d.setDisposable(this._scheduler.scheduleFuture(this, this._d, function (_, self) {
  8456. self._hv && self._id === currentId && self._o.onNext(x);
  8457. self._hv = false;
  8458. }));
  8459. };
  8460. DebounceObserver.prototype.error = function (e) {
  8461. this._c.dispose();
  8462. this._o.onError(e);
  8463. this._hv = false;
  8464. this._id++;
  8465. };
  8466. DebounceObserver.prototype.completed = function () {
  8467. this._c.dispose();
  8468. this._hv && this._o.onNext(this._v);
  8469. this._o.onCompleted();
  8470. this._hv = false;
  8471. this._id++;
  8472. };
  8473. return DebounceObserver;
  8474. }(AbstractObserver));
  8475. function debounceWithSelector(source, durationSelector) {
  8476. return new AnonymousObservable(function (o) {
  8477. var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
  8478. var subscription = source.subscribe(
  8479. function (x) {
  8480. var throttle = tryCatch(durationSelector)(x);
  8481. if (throttle === errorObj) { return o.onError(throttle.e); }
  8482. isPromise(throttle) && (throttle = observableFromPromise(throttle));
  8483. hasValue = true;
  8484. value = x;
  8485. id++;
  8486. var currentid = id, d = new SingleAssignmentDisposable();
  8487. cancelable.setDisposable(d);
  8488. d.setDisposable(throttle.subscribe(
  8489. function () {
  8490. hasValue && id === currentid && o.onNext(value);
  8491. hasValue = false;
  8492. d.dispose();
  8493. },
  8494. function (e) { o.onError(e); },
  8495. function () {
  8496. hasValue && id === currentid && o.onNext(value);
  8497. hasValue = false;
  8498. d.dispose();
  8499. }
  8500. ));
  8501. },
  8502. function (e) {
  8503. cancelable.dispose();
  8504. o.onError(e);
  8505. hasValue = false;
  8506. id++;
  8507. },
  8508. function () {
  8509. cancelable.dispose();
  8510. hasValue && o.onNext(value);
  8511. o.onCompleted();
  8512. hasValue = false;
  8513. id++;
  8514. }
  8515. );
  8516. return new BinaryDisposable(subscription, cancelable);
  8517. }, source);
  8518. }
  8519. observableProto.debounce = function () {
  8520. if (isFunction (arguments[0])) {
  8521. return debounceWithSelector(this, arguments[0]);
  8522. } else if (typeof arguments[0] === 'number') {
  8523. return new DebounceObservable(this, arguments[0], arguments[1]);
  8524. } else {
  8525. throw new Error('Invalid arguments');
  8526. }
  8527. };
  8528. /**
  8529. * Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
  8530. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
  8531. * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
  8532. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
  8533. * @returns {Observable} An observable sequence of windows.
  8534. */
  8535. observableProto.windowWithTime = observableProto.windowTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
  8536. var source = this, timeShift;
  8537. timeShiftOrScheduler == null && (timeShift = timeSpan);
  8538. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8539. if (typeof timeShiftOrScheduler === 'number') {
  8540. timeShift = timeShiftOrScheduler;
  8541. } else if (isScheduler(timeShiftOrScheduler)) {
  8542. timeShift = timeSpan;
  8543. scheduler = timeShiftOrScheduler;
  8544. }
  8545. return new AnonymousObservable(function (observer) {
  8546. var groupDisposable,
  8547. nextShift = timeShift,
  8548. nextSpan = timeSpan,
  8549. q = [],
  8550. refCountDisposable,
  8551. timerD = new SerialDisposable(),
  8552. totalTime = 0;
  8553. groupDisposable = new CompositeDisposable(timerD),
  8554. refCountDisposable = new RefCountDisposable(groupDisposable);
  8555. function createTimer () {
  8556. var m = new SingleAssignmentDisposable(),
  8557. isSpan = false,
  8558. isShift = false;
  8559. timerD.setDisposable(m);
  8560. if (nextSpan === nextShift) {
  8561. isSpan = true;
  8562. isShift = true;
  8563. } else if (nextSpan < nextShift) {
  8564. isSpan = true;
  8565. } else {
  8566. isShift = true;
  8567. }
  8568. var newTotalTime = isSpan ? nextSpan : nextShift,
  8569. ts = newTotalTime - totalTime;
  8570. totalTime = newTotalTime;
  8571. if (isSpan) {
  8572. nextSpan += timeShift;
  8573. }
  8574. if (isShift) {
  8575. nextShift += timeShift;
  8576. }
  8577. m.setDisposable(scheduler.scheduleFuture(null, ts, function () {
  8578. if (isShift) {
  8579. var s = new Subject();
  8580. q.push(s);
  8581. observer.onNext(addRef(s, refCountDisposable));
  8582. }
  8583. isSpan && q.shift().onCompleted();
  8584. createTimer();
  8585. }));
  8586. };
  8587. q.push(new Subject());
  8588. observer.onNext(addRef(q[0], refCountDisposable));
  8589. createTimer();
  8590. groupDisposable.add(source.subscribe(
  8591. function (x) {
  8592. for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
  8593. },
  8594. function (e) {
  8595. for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
  8596. observer.onError(e);
  8597. },
  8598. function () {
  8599. for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
  8600. observer.onCompleted();
  8601. }
  8602. ));
  8603. return refCountDisposable;
  8604. }, source);
  8605. };
  8606. /**
  8607. * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
  8608. * @param {Number} timeSpan Maximum time length of a window.
  8609. * @param {Number} count Maximum element count of a window.
  8610. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
  8611. * @returns {Observable} An observable sequence of windows.
  8612. */
  8613. observableProto.windowWithTimeOrCount = observableProto.windowTimeOrCount = function (timeSpan, count, scheduler) {
  8614. var source = this;
  8615. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8616. return new AnonymousObservable(function (observer) {
  8617. var timerD = new SerialDisposable(),
  8618. groupDisposable = new CompositeDisposable(timerD),
  8619. refCountDisposable = new RefCountDisposable(groupDisposable),
  8620. n = 0,
  8621. windowId = 0,
  8622. s = new Subject();
  8623. function createTimer(id) {
  8624. var m = new SingleAssignmentDisposable();
  8625. timerD.setDisposable(m);
  8626. m.setDisposable(scheduler.scheduleFuture(null, timeSpan, function () {
  8627. if (id !== windowId) { return; }
  8628. n = 0;
  8629. var newId = ++windowId;
  8630. s.onCompleted();
  8631. s = new Subject();
  8632. observer.onNext(addRef(s, refCountDisposable));
  8633. createTimer(newId);
  8634. }));
  8635. }
  8636. observer.onNext(addRef(s, refCountDisposable));
  8637. createTimer(0);
  8638. groupDisposable.add(source.subscribe(
  8639. function (x) {
  8640. var newId = 0, newWindow = false;
  8641. s.onNext(x);
  8642. if (++n === count) {
  8643. newWindow = true;
  8644. n = 0;
  8645. newId = ++windowId;
  8646. s.onCompleted();
  8647. s = new Subject();
  8648. observer.onNext(addRef(s, refCountDisposable));
  8649. }
  8650. newWindow && createTimer(newId);
  8651. },
  8652. function (e) {
  8653. s.onError(e);
  8654. observer.onError(e);
  8655. }, function () {
  8656. s.onCompleted();
  8657. observer.onCompleted();
  8658. }
  8659. ));
  8660. return refCountDisposable;
  8661. }, source);
  8662. };
  8663. function toArray(x) { return x.toArray(); }
  8664. /**
  8665. * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
  8666. * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
  8667. * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
  8668. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
  8669. * @returns {Observable} An observable sequence of buffers.
  8670. */
  8671. observableProto.bufferWithTime = observableProto.bufferTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
  8672. return this.windowWithTime(timeSpan, timeShiftOrScheduler, scheduler).flatMap(toArray);
  8673. };
  8674. function toArray(x) { return x.toArray(); }
  8675. /**
  8676. * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
  8677. * @param {Number} timeSpan Maximum time length of a buffer.
  8678. * @param {Number} count Maximum element count of a buffer.
  8679. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
  8680. * @returns {Observable} An observable sequence of buffers.
  8681. */
  8682. observableProto.bufferWithTimeOrCount = observableProto.bufferTimeOrCount = function (timeSpan, count, scheduler) {
  8683. return this.windowWithTimeOrCount(timeSpan, count, scheduler).flatMap(toArray);
  8684. };
  8685. var TimeIntervalObservable = (function (__super__) {
  8686. inherits(TimeIntervalObservable, __super__);
  8687. function TimeIntervalObservable(source, s) {
  8688. this.source = source;
  8689. this._s = s;
  8690. __super__.call(this);
  8691. }
  8692. TimeIntervalObservable.prototype.subscribeCore = function (o) {
  8693. return this.source.subscribe(new TimeIntervalObserver(o, this._s));
  8694. };
  8695. return TimeIntervalObservable;
  8696. }(ObservableBase));
  8697. var TimeIntervalObserver = (function (__super__) {
  8698. inherits(TimeIntervalObserver, __super__);
  8699. function TimeIntervalObserver(o, s) {
  8700. this._o = o;
  8701. this._s = s;
  8702. this._l = s.now();
  8703. __super__.call(this);
  8704. }
  8705. TimeIntervalObserver.prototype.next = function (x) {
  8706. var now = this._s.now(), span = now - this._l;
  8707. this._l = now;
  8708. this._o.onNext({ value: x, interval: span });
  8709. };
  8710. TimeIntervalObserver.prototype.error = function (e) { this._o.onError(e); };
  8711. TimeIntervalObserver.prototype.completed = function () { this._o.onCompleted(); };
  8712. return TimeIntervalObserver;
  8713. }(AbstractObserver));
  8714. /**
  8715. * Records the time interval between consecutive values in an observable sequence.
  8716. *
  8717. * @example
  8718. * 1 - res = source.timeInterval();
  8719. * 2 - res = source.timeInterval(Rx.Scheduler.timeout);
  8720. *
  8721. * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
  8722. * @returns {Observable} An observable sequence with time interval information on values.
  8723. */
  8724. observableProto.timeInterval = function (scheduler) {
  8725. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8726. return new TimeIntervalObservable(this, scheduler);
  8727. };
  8728. var TimestampObservable = (function (__super__) {
  8729. inherits(TimestampObservable, __super__);
  8730. function TimestampObservable(source, s) {
  8731. this.source = source;
  8732. this._s = s;
  8733. __super__.call(this);
  8734. }
  8735. TimestampObservable.prototype.subscribeCore = function (o) {
  8736. return this.source.subscribe(new TimestampObserver(o, this._s));
  8737. };
  8738. return TimestampObservable;
  8739. }(ObservableBase));
  8740. var TimestampObserver = (function (__super__) {
  8741. inherits(TimestampObserver, __super__);
  8742. function TimestampObserver(o, s) {
  8743. this._o = o;
  8744. this._s = s;
  8745. __super__.call(this);
  8746. }
  8747. TimestampObserver.prototype.next = function (x) {
  8748. this._o.onNext({ value: x, timestamp: this._s.now() });
  8749. };
  8750. TimestampObserver.prototype.error = function (e) {
  8751. this._o.onError(e);
  8752. };
  8753. TimestampObserver.prototype.completed = function () {
  8754. this._o.onCompleted();
  8755. };
  8756. return TimestampObserver;
  8757. }(AbstractObserver));
  8758. /**
  8759. * Records the timestamp for each value in an observable sequence.
  8760. *
  8761. * @example
  8762. * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
  8763. * 2 - res = source.timestamp(Rx.Scheduler.default);
  8764. *
  8765. * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used.
  8766. * @returns {Observable} An observable sequence with timestamp information on values.
  8767. */
  8768. observableProto.timestamp = function (scheduler) {
  8769. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8770. return new TimestampObservable(this, scheduler);
  8771. };
  8772. var SampleObservable = (function(__super__) {
  8773. inherits(SampleObservable, __super__);
  8774. function SampleObservable(source, sampler) {
  8775. this.source = source;
  8776. this._sampler = sampler;
  8777. __super__.call(this);
  8778. }
  8779. SampleObservable.prototype.subscribeCore = function (o) {
  8780. var state = {
  8781. o: o,
  8782. atEnd: false,
  8783. value: null,
  8784. hasValue: false,
  8785. sourceSubscription: new SingleAssignmentDisposable()
  8786. };
  8787. state.sourceSubscription.setDisposable(this.source.subscribe(new SampleSourceObserver(state)));
  8788. return new BinaryDisposable(
  8789. state.sourceSubscription,
  8790. this._sampler.subscribe(new SamplerObserver(state))
  8791. );
  8792. };
  8793. return SampleObservable;
  8794. }(ObservableBase));
  8795. var SamplerObserver = (function(__super__) {
  8796. inherits(SamplerObserver, __super__);
  8797. function SamplerObserver(s) {
  8798. this._s = s;
  8799. __super__.call(this);
  8800. }
  8801. SamplerObserver.prototype._handleMessage = function () {
  8802. if (this._s.hasValue) {
  8803. this._s.hasValue = false;
  8804. this._s.o.onNext(this._s.value);
  8805. }
  8806. this._s.atEnd && this._s.o.onCompleted();
  8807. };
  8808. SamplerObserver.prototype.next = function () { this._handleMessage(); };
  8809. SamplerObserver.prototype.error = function (e) { this._s.onError(e); };
  8810. SamplerObserver.prototype.completed = function () { this._handleMessage(); };
  8811. return SamplerObserver;
  8812. }(AbstractObserver));
  8813. var SampleSourceObserver = (function(__super__) {
  8814. inherits(SampleSourceObserver, __super__);
  8815. function SampleSourceObserver(s) {
  8816. this._s = s;
  8817. __super__.call(this);
  8818. }
  8819. SampleSourceObserver.prototype.next = function (x) {
  8820. this._s.hasValue = true;
  8821. this._s.value = x;
  8822. };
  8823. SampleSourceObserver.prototype.error = function (e) { this._s.o.onError(e); };
  8824. SampleSourceObserver.prototype.completed = function () {
  8825. this._s.atEnd = true;
  8826. this._s.sourceSubscription.dispose();
  8827. };
  8828. return SampleSourceObserver;
  8829. }(AbstractObserver));
  8830. /**
  8831. * Samples the observable sequence at each interval.
  8832. *
  8833. * @example
  8834. * 1 - res = source.sample(sampleObservable); // Sampler tick sequence
  8835. * 2 - res = source.sample(5000); // 5 seconds
  8836. * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
  8837. *
  8838. * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
  8839. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
  8840. * @returns {Observable} Sampled observable sequence.
  8841. */
  8842. observableProto.sample = function (intervalOrSampler, scheduler) {
  8843. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8844. return typeof intervalOrSampler === 'number' ?
  8845. new SampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
  8846. new SampleObservable(this, intervalOrSampler);
  8847. };
  8848. var TimeoutError = Rx.TimeoutError = function(message) {
  8849. this.message = message || 'Timeout has occurred';
  8850. this.name = 'TimeoutError';
  8851. Error.call(this);
  8852. };
  8853. TimeoutError.prototype = Object.create(Error.prototype);
  8854. function timeoutWithSelector(source, firstTimeout, timeoutDurationSelector, other) {
  8855. if (isFunction(firstTimeout)) {
  8856. other = timeoutDurationSelector;
  8857. timeoutDurationSelector = firstTimeout;
  8858. firstTimeout = observableNever();
  8859. }
  8860. Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
  8861. return new AnonymousObservable(function (o) {
  8862. var subscription = new SerialDisposable(),
  8863. timer = new SerialDisposable(),
  8864. original = new SingleAssignmentDisposable();
  8865. subscription.setDisposable(original);
  8866. var id = 0, switched = false;
  8867. function setTimer(timeout) {
  8868. var myId = id, d = new SingleAssignmentDisposable();
  8869. function timerWins() {
  8870. switched = (myId === id);
  8871. return switched;
  8872. }
  8873. timer.setDisposable(d);
  8874. d.setDisposable(timeout.subscribe(function () {
  8875. timerWins() && subscription.setDisposable(other.subscribe(o));
  8876. d.dispose();
  8877. }, function (e) {
  8878. timerWins() && o.onError(e);
  8879. }, function () {
  8880. timerWins() && subscription.setDisposable(other.subscribe(o));
  8881. }));
  8882. };
  8883. setTimer(firstTimeout);
  8884. function oWins() {
  8885. var res = !switched;
  8886. if (res) { id++; }
  8887. return res;
  8888. }
  8889. original.setDisposable(source.subscribe(function (x) {
  8890. if (oWins()) {
  8891. o.onNext(x);
  8892. var timeout = tryCatch(timeoutDurationSelector)(x);
  8893. if (timeout === errorObj) { return o.onError(timeout.e); }
  8894. setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
  8895. }
  8896. }, function (e) {
  8897. oWins() && o.onError(e);
  8898. }, function () {
  8899. oWins() && o.onCompleted();
  8900. }));
  8901. return new BinaryDisposable(subscription, timer);
  8902. }, source);
  8903. }
  8904. function timeout(source, dueTime, other, scheduler) {
  8905. if (isScheduler(other)) {
  8906. scheduler = other;
  8907. other = observableThrow(new TimeoutError());
  8908. }
  8909. if (other instanceof Error) { other = observableThrow(other); }
  8910. isScheduler(scheduler) || (scheduler = defaultScheduler);
  8911. Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
  8912. return new AnonymousObservable(function (o) {
  8913. var id = 0,
  8914. original = new SingleAssignmentDisposable(),
  8915. subscription = new SerialDisposable(),
  8916. switched = false,
  8917. timer = new SerialDisposable();
  8918. subscription.setDisposable(original);
  8919. function createTimer() {
  8920. var myId = id;
  8921. timer.setDisposable(scheduler.scheduleFuture(null, dueTime, function () {
  8922. switched = id === myId;
  8923. if (switched) {
  8924. isPromise(other) && (other = observableFromPromise(other));
  8925. subscription.setDisposable(other.subscribe(o));
  8926. }
  8927. }));
  8928. }
  8929. createTimer();
  8930. original.setDisposable(source.subscribe(function (x) {
  8931. if (!switched) {
  8932. id++;
  8933. o.onNext(x);
  8934. createTimer();
  8935. }
  8936. }, function (e) {
  8937. if (!switched) {
  8938. id++;
  8939. o.onError(e);
  8940. }
  8941. }, function () {
  8942. if (!switched) {
  8943. id++;
  8944. o.onCompleted();
  8945. }
  8946. }));
  8947. return new BinaryDisposable(subscription, timer);
  8948. }, source);
  8949. }
  8950. observableProto.timeout = function () {
  8951. var firstArg = arguments[0];
  8952. if (firstArg instanceof Date || typeof firstArg === 'number') {
  8953. return timeout(this, firstArg, arguments[1], arguments[2]);
  8954. } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
  8955. return timeoutWithSelector(this, firstArg, arguments[1], arguments[2]);
  8956. } else {
  8957. throw new Error('Invalid arguments');
  8958. }
  8959. };
  8960. var GenerateAbsoluteObservable = (function (__super__) {
  8961. inherits(GenerateAbsoluteObservable, __super__);
  8962. function GenerateAbsoluteObservable(state, cndFn, itrFn, resFn, timeFn, s) {
  8963. this._state = state;
  8964. this._cndFn = cndFn;
  8965. this._itrFn = itrFn;
  8966. this._resFn = resFn;
  8967. this._timeFn = timeFn;
  8968. this._s = s;
  8969. __super__.call(this);
  8970. }
  8971. function scheduleRecursive(state, recurse) {
  8972. state.hasResult && state.o.onNext(state.result);
  8973. if (state.first) {
  8974. state.first = false;
  8975. } else {
  8976. state.newState = tryCatch(state.self._itrFn)(state.newState);
  8977. if (state.newState === errorObj) { return state.o.onError(state.newState.e); }
  8978. }
  8979. state.hasResult = tryCatch(state.self._cndFn)(state.newState);
  8980. if (state.hasResult === errorObj) { return state.o.onError(state.hasResult.e); }
  8981. if (state.hasResult) {
  8982. state.result = tryCatch(state.self._resFn)(state.newState);
  8983. if (state.result === errorObj) { return state.o.onError(state.result.e); }
  8984. var time = tryCatch(state.self._timeFn)(state.newState);
  8985. if (time === errorObj) { return state.o.onError(time.e); }
  8986. recurse(state, time);
  8987. } else {
  8988. state.o.onCompleted();
  8989. }
  8990. }
  8991. GenerateAbsoluteObservable.prototype.subscribeCore = function (o) {
  8992. var state = {
  8993. o: o,
  8994. self: this,
  8995. newState: this._state,
  8996. first: true,
  8997. hasResult: false
  8998. };
  8999. return this._s.scheduleRecursiveFuture(state, new Date(this._s.now()), scheduleRecursive);
  9000. };
  9001. return GenerateAbsoluteObservable;
  9002. }(ObservableBase));
  9003. /**
  9004. * GenerateAbsolutes an observable sequence by iterating a state from an initial state until the condition fails.
  9005. *
  9006. * @example
  9007. * res = source.generateWithAbsoluteTime(0,
  9008. * function (x) { return return true; },
  9009. * function (x) { return x + 1; },
  9010. * function (x) { return x; },
  9011. * function (x) { return new Date(); }
  9012. * });
  9013. *
  9014. * @param {Mixed} initialState Initial state.
  9015. * @param {Function} condition Condition to terminate generation (upon returning false).
  9016. * @param {Function} iterate Iteration step function.
  9017. * @param {Function} resultSelector Selector function for results produced in the sequence.
  9018. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
  9019. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
  9020. * @returns {Observable} The generated sequence.
  9021. */
  9022. Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
  9023. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9024. return new GenerateAbsoluteObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler);
  9025. };
  9026. var GenerateRelativeObservable = (function (__super__) {
  9027. inherits(GenerateRelativeObservable, __super__);
  9028. function GenerateRelativeObservable(state, cndFn, itrFn, resFn, timeFn, s) {
  9029. this._state = state;
  9030. this._cndFn = cndFn;
  9031. this._itrFn = itrFn;
  9032. this._resFn = resFn;
  9033. this._timeFn = timeFn;
  9034. this._s = s;
  9035. __super__.call(this);
  9036. }
  9037. function scheduleRecursive(state, recurse) {
  9038. state.hasResult && state.o.onNext(state.result);
  9039. if (state.first) {
  9040. state.first = false;
  9041. } else {
  9042. state.newState = tryCatch(state.self._itrFn)(state.newState);
  9043. if (state.newState === errorObj) { return state.o.onError(state.newState.e); }
  9044. }
  9045. state.hasResult = tryCatch(state.self._cndFn)(state.newState);
  9046. if (state.hasResult === errorObj) { return state.o.onError(state.hasResult.e); }
  9047. if (state.hasResult) {
  9048. state.result = tryCatch(state.self._resFn)(state.newState);
  9049. if (state.result === errorObj) { return state.o.onError(state.result.e); }
  9050. var time = tryCatch(state.self._timeFn)(state.newState);
  9051. if (time === errorObj) { return state.o.onError(time.e); }
  9052. recurse(state, time);
  9053. } else {
  9054. state.o.onCompleted();
  9055. }
  9056. }
  9057. GenerateRelativeObservable.prototype.subscribeCore = function (o) {
  9058. var state = {
  9059. o: o,
  9060. self: this,
  9061. newState: this._state,
  9062. first: true,
  9063. hasResult: false
  9064. };
  9065. return this._s.scheduleRecursiveFuture(state, 0, scheduleRecursive);
  9066. };
  9067. return GenerateRelativeObservable;
  9068. }(ObservableBase));
  9069. /**
  9070. * Generates an observable sequence by iterating a state from an initial state until the condition fails.
  9071. *
  9072. * @example
  9073. * res = source.generateWithRelativeTime(0,
  9074. * function (x) { return return true; },
  9075. * function (x) { return x + 1; },
  9076. * function (x) { return x; },
  9077. * function (x) { return 500; }
  9078. * );
  9079. *
  9080. * @param {Mixed} initialState Initial state.
  9081. * @param {Function} condition Condition to terminate generation (upon returning false).
  9082. * @param {Function} iterate Iteration step function.
  9083. * @param {Function} resultSelector Selector function for results produced in the sequence.
  9084. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
  9085. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
  9086. * @returns {Observable} The generated sequence.
  9087. */
  9088. Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
  9089. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9090. return new GenerateRelativeObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler);
  9091. };
  9092. var DelaySubscription = (function(__super__) {
  9093. inherits(DelaySubscription, __super__);
  9094. function DelaySubscription(source, dt, s) {
  9095. this.source = source;
  9096. this._dt = dt;
  9097. this._s = s;
  9098. __super__.call(this);
  9099. }
  9100. DelaySubscription.prototype.subscribeCore = function (o) {
  9101. var d = new SerialDisposable();
  9102. d.setDisposable(this._s.scheduleFuture([this.source, o, d], this._dt, scheduleMethod));
  9103. return d;
  9104. };
  9105. function scheduleMethod(s, state) {
  9106. var source = state[0], o = state[1], d = state[2];
  9107. d.setDisposable(source.subscribe(o));
  9108. }
  9109. return DelaySubscription;
  9110. }(ObservableBase));
  9111. /**
  9112. * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
  9113. *
  9114. * @example
  9115. * 1 - res = source.delaySubscription(5000); // 5s
  9116. * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds
  9117. *
  9118. * @param {Number} dueTime Relative or absolute time shift of the subscription.
  9119. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
  9120. * @returns {Observable} Time-shifted sequence.
  9121. */
  9122. observableProto.delaySubscription = function (dueTime, scheduler) {
  9123. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9124. return new DelaySubscription(this, dueTime, scheduler);
  9125. };
  9126. var SkipLastWithTimeObservable = (function (__super__) {
  9127. inherits(SkipLastWithTimeObservable, __super__);
  9128. function SkipLastWithTimeObservable(source, d, s) {
  9129. this.source = source;
  9130. this._d = d;
  9131. this._s = s;
  9132. __super__.call(this);
  9133. }
  9134. SkipLastWithTimeObservable.prototype.subscribeCore = function (o) {
  9135. return this.source.subscribe(new SkipLastWithTimeObserver(o, this));
  9136. };
  9137. return SkipLastWithTimeObservable;
  9138. }(ObservableBase));
  9139. var SkipLastWithTimeObserver = (function (__super__) {
  9140. inherits(SkipLastWithTimeObserver, __super__);
  9141. function SkipLastWithTimeObserver(o, p) {
  9142. this._o = o;
  9143. this._s = p._s;
  9144. this._d = p._d;
  9145. this._q = [];
  9146. __super__.call(this);
  9147. }
  9148. SkipLastWithTimeObserver.prototype.next = function (x) {
  9149. var now = this._s.now();
  9150. this._q.push({ interval: now, value: x });
  9151. while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
  9152. this._o.onNext(this._q.shift().value);
  9153. }
  9154. };
  9155. SkipLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
  9156. SkipLastWithTimeObserver.prototype.completed = function () {
  9157. var now = this._s.now();
  9158. while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
  9159. this._o.onNext(this._q.shift().value);
  9160. }
  9161. this._o.onCompleted();
  9162. };
  9163. return SkipLastWithTimeObserver;
  9164. }(AbstractObserver));
  9165. /**
  9166. * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
  9167. * @description
  9168. * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
  9169. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
  9170. * result sequence. This causes elements to be delayed with duration.
  9171. * @param {Number} duration Duration for skipping elements from the end of the sequence.
  9172. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
  9173. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
  9174. */
  9175. observableProto.skipLastWithTime = function (duration, scheduler) {
  9176. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9177. return new SkipLastWithTimeObservable(this, duration, scheduler);
  9178. };
  9179. var TakeLastWithTimeObservable = (function (__super__) {
  9180. inherits(TakeLastWithTimeObservable, __super__);
  9181. function TakeLastWithTimeObservable(source, d, s) {
  9182. this.source = source;
  9183. this._d = d;
  9184. this._s = s;
  9185. __super__.call(this);
  9186. }
  9187. TakeLastWithTimeObservable.prototype.subscribeCore = function (o) {
  9188. return this.source.subscribe(new TakeLastWithTimeObserver(o, this._d, this._s));
  9189. };
  9190. return TakeLastWithTimeObservable;
  9191. }(ObservableBase));
  9192. var TakeLastWithTimeObserver = (function (__super__) {
  9193. inherits(TakeLastWithTimeObserver, __super__);
  9194. function TakeLastWithTimeObserver(o, d, s) {
  9195. this._o = o;
  9196. this._d = d;
  9197. this._s = s;
  9198. this._q = [];
  9199. __super__.call(this);
  9200. }
  9201. TakeLastWithTimeObserver.prototype.next = function (x) {
  9202. var now = this._s.now();
  9203. this._q.push({ interval: now, value: x });
  9204. while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
  9205. this._q.shift();
  9206. }
  9207. };
  9208. TakeLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
  9209. TakeLastWithTimeObserver.prototype.completed = function () {
  9210. var now = this._s.now();
  9211. while (this._q.length > 0) {
  9212. var next = this._q.shift();
  9213. if (now - next.interval <= this._d) { this._o.onNext(next.value); }
  9214. }
  9215. this._o.onCompleted();
  9216. };
  9217. return TakeLastWithTimeObserver;
  9218. }(AbstractObserver));
  9219. /**
  9220. * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
  9221. * @description
  9222. * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
  9223. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
  9224. * result sequence. This causes elements to be delayed with duration.
  9225. * @param {Number} duration Duration for taking elements from the end of the sequence.
  9226. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
  9227. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
  9228. */
  9229. observableProto.takeLastWithTime = function (duration, scheduler) {
  9230. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9231. return new TakeLastWithTimeObservable(this, duration, scheduler);
  9232. };
  9233. /**
  9234. * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
  9235. * @description
  9236. * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
  9237. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
  9238. * result sequence. This causes elements to be delayed with duration.
  9239. * @param {Number} duration Duration for taking elements from the end of the sequence.
  9240. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
  9241. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
  9242. */
  9243. observableProto.takeLastBufferWithTime = function (duration, scheduler) {
  9244. var source = this;
  9245. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9246. return new AnonymousObservable(function (o) {
  9247. var q = [];
  9248. return source.subscribe(function (x) {
  9249. var now = scheduler.now();
  9250. q.push({ interval: now, value: x });
  9251. while (q.length > 0 && now - q[0].interval >= duration) {
  9252. q.shift();
  9253. }
  9254. }, function (e) { o.onError(e); }, function () {
  9255. var now = scheduler.now(), res = [];
  9256. while (q.length > 0) {
  9257. var next = q.shift();
  9258. now - next.interval <= duration && res.push(next.value);
  9259. }
  9260. o.onNext(res);
  9261. o.onCompleted();
  9262. });
  9263. }, source);
  9264. };
  9265. var TakeWithTimeObservable = (function (__super__) {
  9266. inherits(TakeWithTimeObservable, __super__);
  9267. function TakeWithTimeObservable(source, d, s) {
  9268. this.source = source;
  9269. this._d = d;
  9270. this._s = s;
  9271. __super__.call(this);
  9272. }
  9273. function scheduleMethod(s, o) {
  9274. o.onCompleted();
  9275. }
  9276. TakeWithTimeObservable.prototype.subscribeCore = function (o) {
  9277. return new BinaryDisposable(
  9278. this._s.scheduleFuture(o, this._d, scheduleMethod),
  9279. this.source.subscribe(o)
  9280. );
  9281. };
  9282. return TakeWithTimeObservable;
  9283. }(ObservableBase));
  9284. /**
  9285. * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
  9286. *
  9287. * @example
  9288. * 1 - res = source.takeWithTime(5000, [optional scheduler]);
  9289. * @description
  9290. * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
  9291. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
  9292. * result sequence. This causes elements to be delayed with duration.
  9293. * @param {Number} duration Duration for taking elements from the start of the sequence.
  9294. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
  9295. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
  9296. */
  9297. observableProto.takeWithTime = function (duration, scheduler) {
  9298. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9299. return new TakeWithTimeObservable(this, duration, scheduler);
  9300. };
  9301. var SkipWithTimeObservable = (function (__super__) {
  9302. inherits(SkipWithTimeObservable, __super__);
  9303. function SkipWithTimeObservable(source, d, s) {
  9304. this.source = source;
  9305. this._d = d;
  9306. this._s = s;
  9307. this._open = false;
  9308. __super__.call(this);
  9309. }
  9310. function scheduleMethod(s, self) {
  9311. self._open = true;
  9312. }
  9313. SkipWithTimeObservable.prototype.subscribeCore = function (o) {
  9314. return new BinaryDisposable(
  9315. this._s.scheduleFuture(this, this._d, scheduleMethod),
  9316. this.source.subscribe(new SkipWithTimeObserver(o, this))
  9317. );
  9318. };
  9319. return SkipWithTimeObservable;
  9320. }(ObservableBase));
  9321. var SkipWithTimeObserver = (function (__super__) {
  9322. inherits(SkipWithTimeObserver, __super__);
  9323. function SkipWithTimeObserver(o, p) {
  9324. this._o = o;
  9325. this._p = p;
  9326. __super__.call(this);
  9327. }
  9328. SkipWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); };
  9329. SkipWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
  9330. SkipWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); };
  9331. return SkipWithTimeObserver;
  9332. }(AbstractObserver));
  9333. /**
  9334. * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
  9335. * @description
  9336. * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
  9337. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
  9338. * may not execute immediately, despite the zero due time.
  9339. *
  9340. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
  9341. * @param {Number} duration Duration for skipping elements from the start of the sequence.
  9342. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
  9343. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
  9344. */
  9345. observableProto.skipWithTime = function (duration, scheduler) {
  9346. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9347. return new SkipWithTimeObservable(this, duration, scheduler);
  9348. };
  9349. var SkipUntilWithTimeObservable = (function (__super__) {
  9350. inherits(SkipUntilWithTimeObservable, __super__);
  9351. function SkipUntilWithTimeObservable(source, startTime, scheduler) {
  9352. this.source = source;
  9353. this._st = startTime;
  9354. this._s = scheduler;
  9355. __super__.call(this);
  9356. }
  9357. function scheduleMethod(s, state) {
  9358. state._open = true;
  9359. }
  9360. SkipUntilWithTimeObservable.prototype.subscribeCore = function (o) {
  9361. this._open = false;
  9362. return new BinaryDisposable(
  9363. this._s.scheduleFuture(this, this._st, scheduleMethod),
  9364. this.source.subscribe(new SkipUntilWithTimeObserver(o, this))
  9365. );
  9366. };
  9367. return SkipUntilWithTimeObservable;
  9368. }(ObservableBase));
  9369. var SkipUntilWithTimeObserver = (function (__super__) {
  9370. inherits(SkipUntilWithTimeObserver, __super__);
  9371. function SkipUntilWithTimeObserver(o, p) {
  9372. this._o = o;
  9373. this._p = p;
  9374. __super__.call(this);
  9375. }
  9376. SkipUntilWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); };
  9377. SkipUntilWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
  9378. SkipUntilWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); };
  9379. return SkipUntilWithTimeObserver;
  9380. }(AbstractObserver));
  9381. /**
  9382. * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
  9383. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
  9384. *
  9385. * @examples
  9386. * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
  9387. * 2 - res = source.skipUntilWithTime(5000, [scheduler]);
  9388. * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
  9389. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
  9390. * @returns {Observable} An observable sequence with the elements skipped until the specified start time.
  9391. */
  9392. observableProto.skipUntilWithTime = function (startTime, scheduler) {
  9393. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9394. return new SkipUntilWithTimeObservable(this, startTime, scheduler);
  9395. };
  9396. /**
  9397. * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
  9398. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
  9399. * @param {Scheduler} [scheduler] Scheduler to run the timer on.
  9400. * @returns {Observable} An observable sequence with the elements taken until the specified end time.
  9401. */
  9402. observableProto.takeUntilWithTime = function (endTime, scheduler) {
  9403. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9404. var source = this;
  9405. return new AnonymousObservable(function (o) {
  9406. return new BinaryDisposable(
  9407. scheduler.scheduleFuture(o, endTime, function (_, o) { o.onCompleted(); }),
  9408. source.subscribe(o));
  9409. }, source);
  9410. };
  9411. /**
  9412. * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
  9413. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item
  9414. * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
  9415. * @returns {Observable} An Observable that performs the throttle operation.
  9416. */
  9417. observableProto.throttle = function (windowDuration, scheduler) {
  9418. isScheduler(scheduler) || (scheduler = defaultScheduler);
  9419. var duration = +windowDuration || 0;
  9420. if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
  9421. var source = this;
  9422. return new AnonymousObservable(function (o) {
  9423. var lastOnNext = 0;
  9424. return source.subscribe(
  9425. function (x) {
  9426. var now = scheduler.now();
  9427. if (lastOnNext === 0 || now - lastOnNext >= duration) {
  9428. lastOnNext = now;
  9429. o.onNext(x);
  9430. }
  9431. },function (e) { o.onError(e); }, function () { o.onCompleted(); }
  9432. );
  9433. }, source);
  9434. };
  9435. var TransduceObserver = (function (__super__) {
  9436. inherits(TransduceObserver, __super__);
  9437. function TransduceObserver(o, xform) {
  9438. this._o = o;
  9439. this._xform = xform;
  9440. __super__.call(this);
  9441. }
  9442. TransduceObserver.prototype.next = function (x) {
  9443. var res = tryCatch(this._xform['@@transducer/step']).call(this._xform, this._o, x);
  9444. if (res === errorObj) { this._o.onError(res.e); }
  9445. };
  9446. TransduceObserver.prototype.error = function (e) { this._o.onError(e); };
  9447. TransduceObserver.prototype.completed = function () {
  9448. this._xform['@@transducer/result'](this._o);
  9449. };
  9450. return TransduceObserver;
  9451. }(AbstractObserver));
  9452. function transformForObserver(o) {
  9453. return {
  9454. '@@transducer/init': function() {
  9455. return o;
  9456. },
  9457. '@@transducer/step': function(obs, input) {
  9458. return obs.onNext(input);
  9459. },
  9460. '@@transducer/result': function(obs) {
  9461. return obs.onCompleted();
  9462. }
  9463. };
  9464. }
  9465. /**
  9466. * Executes a transducer to transform the observable sequence
  9467. * @param {Transducer} transducer A transducer to execute
  9468. * @returns {Observable} An Observable sequence containing the results from the transducer.
  9469. */
  9470. observableProto.transduce = function(transducer) {
  9471. var source = this;
  9472. return new AnonymousObservable(function(o) {
  9473. var xform = transducer(transformForObserver(o));
  9474. return source.subscribe(new TransduceObserver(o, xform));
  9475. }, source);
  9476. };
  9477. var SwitchFirstObservable = (function (__super__) {
  9478. inherits(SwitchFirstObservable, __super__);
  9479. function SwitchFirstObservable(source) {
  9480. this.source = source;
  9481. __super__.call(this);
  9482. }
  9483. SwitchFirstObservable.prototype.subscribeCore = function (o) {
  9484. var m = new SingleAssignmentDisposable(),
  9485. g = new CompositeDisposable(),
  9486. state = {
  9487. hasCurrent: false,
  9488. isStopped: false,
  9489. o: o,
  9490. g: g
  9491. };
  9492. g.add(m);
  9493. m.setDisposable(this.source.subscribe(new SwitchFirstObserver(state)));
  9494. return g;
  9495. };
  9496. return SwitchFirstObservable;
  9497. }(ObservableBase));
  9498. var SwitchFirstObserver = (function(__super__) {
  9499. inherits(SwitchFirstObserver, __super__);
  9500. function SwitchFirstObserver(state) {
  9501. this._s = state;
  9502. __super__.call(this);
  9503. }
  9504. SwitchFirstObserver.prototype.next = function (x) {
  9505. if (!this._s.hasCurrent) {
  9506. this._s.hasCurrent = true;
  9507. isPromise(x) && (x = observableFromPromise(x));
  9508. var inner = new SingleAssignmentDisposable();
  9509. this._s.g.add(inner);
  9510. inner.setDisposable(x.subscribe(new InnerObserver(this._s, inner)));
  9511. }
  9512. };
  9513. SwitchFirstObserver.prototype.error = function (e) {
  9514. this._s.o.onError(e);
  9515. };
  9516. SwitchFirstObserver.prototype.completed = function () {
  9517. this._s.isStopped = true;
  9518. !this._s.hasCurrent && this._s.g.length === 1 && this._s.o.onCompleted();
  9519. };
  9520. inherits(InnerObserver, __super__);
  9521. function InnerObserver(state, inner) {
  9522. this._s = state;
  9523. this._i = inner;
  9524. __super__.call(this);
  9525. }
  9526. InnerObserver.prototype.next = function (x) { this._s.o.onNext(x); };
  9527. InnerObserver.prototype.error = function (e) { this._s.o.onError(e); };
  9528. InnerObserver.prototype.completed = function () {
  9529. this._s.g.remove(this._i);
  9530. this._s.hasCurrent = false;
  9531. this._s.isStopped && this._s.g.length === 1 && this._s.o.onCompleted();
  9532. };
  9533. return SwitchFirstObserver;
  9534. }(AbstractObserver));
  9535. /**
  9536. * Performs a exclusive waiting for the first to finish before subscribing to another observable.
  9537. * Observables that come in between subscriptions will be dropped on the floor.
  9538. * @returns {Observable} A exclusive observable with only the results that happen when subscribed.
  9539. */
  9540. observableProto.switchFirst = function () {
  9541. return new SwitchFirstObservable(this);
  9542. };
  9543. observableProto.flatMapFirst = observableProto.exhaustMap = function(selector, resultSelector, thisArg) {
  9544. return new FlatMapObservable(this, selector, resultSelector, thisArg).switchFirst();
  9545. };
  9546. observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent = function(limit, selector, resultSelector, thisArg) {
  9547. return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(limit);
  9548. };
  9549. /** Provides a set of extension methods for virtual time scheduling. */
  9550. var VirtualTimeScheduler = Rx.VirtualTimeScheduler = (function (__super__) {
  9551. inherits(VirtualTimeScheduler, __super__);
  9552. /**
  9553. * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
  9554. *
  9555. * @constructor
  9556. * @param {Number} initialClock Initial value for the clock.
  9557. * @param {Function} comparer Comparer to determine causality of events based on absolute time.
  9558. */
  9559. function VirtualTimeScheduler(initialClock, comparer) {
  9560. this.clock = initialClock;
  9561. this.comparer = comparer;
  9562. this.isEnabled = false;
  9563. this.queue = new PriorityQueue(1024);
  9564. __super__.call(this);
  9565. }
  9566. var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
  9567. VirtualTimeSchedulerPrototype.now = function () {
  9568. return this.toAbsoluteTime(this.clock);
  9569. };
  9570. VirtualTimeSchedulerPrototype.schedule = function (state, action) {
  9571. return this.scheduleAbsolute(state, this.clock, action);
  9572. };
  9573. VirtualTimeSchedulerPrototype.scheduleFuture = function (state, dueTime, action) {
  9574. var dt = dueTime instanceof Date ?
  9575. this.toRelativeTime(dueTime - this.now()) :
  9576. this.toRelativeTime(dueTime);
  9577. return this.scheduleRelative(state, dt, action);
  9578. };
  9579. /**
  9580. * Adds a relative time value to an absolute time value.
  9581. * @param {Number} absolute Absolute virtual time value.
  9582. * @param {Number} relative Relative virtual time value to add.
  9583. * @return {Number} Resulting absolute virtual time sum value.
  9584. */
  9585. VirtualTimeSchedulerPrototype.add = notImplemented;
  9586. /**
  9587. * Converts an absolute time to a number
  9588. * @param {Any} The absolute time.
  9589. * @returns {Number} The absolute time in ms
  9590. */
  9591. VirtualTimeSchedulerPrototype.toAbsoluteTime = notImplemented;
  9592. /**
  9593. * Converts the TimeSpan value to a relative virtual time value.
  9594. * @param {Number} timeSpan TimeSpan value to convert.
  9595. * @return {Number} Corresponding relative virtual time value.
  9596. */
  9597. VirtualTimeSchedulerPrototype.toRelativeTime = notImplemented;
  9598. /**
  9599. * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
  9600. * @param {Mixed} state Initial state passed to the action upon the first iteration.
  9601. * @param {Number} period Period for running the work periodically.
  9602. * @param {Function} action Action to be executed, potentially updating the state.
  9603. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
  9604. */
  9605. VirtualTimeSchedulerPrototype.schedulePeriodic = function (state, period, action) {
  9606. var s = new SchedulePeriodicRecursive(this, state, period, action);
  9607. return s.start();
  9608. };
  9609. /**
  9610. * Schedules an action to be executed after dueTime.
  9611. * @param {Mixed} state State passed to the action to be executed.
  9612. * @param {Number} dueTime Relative time after which to execute the action.
  9613. * @param {Function} action Action to be executed.
  9614. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  9615. */
  9616. VirtualTimeSchedulerPrototype.scheduleRelative = function (state, dueTime, action) {
  9617. var runAt = this.add(this.clock, dueTime);
  9618. return this.scheduleAbsolute(state, runAt, action);
  9619. };
  9620. /**
  9621. * Starts the virtual time scheduler.
  9622. */
  9623. VirtualTimeSchedulerPrototype.start = function () {
  9624. if (!this.isEnabled) {
  9625. this.isEnabled = true;
  9626. do {
  9627. var next = this.getNext();
  9628. if (next !== null) {
  9629. this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
  9630. next.invoke();
  9631. } else {
  9632. this.isEnabled = false;
  9633. }
  9634. } while (this.isEnabled);
  9635. }
  9636. };
  9637. /**
  9638. * Stops the virtual time scheduler.
  9639. */
  9640. VirtualTimeSchedulerPrototype.stop = function () {
  9641. this.isEnabled = false;
  9642. };
  9643. /**
  9644. * Advances the scheduler's clock to the specified time, running all work till that point.
  9645. * @param {Number} time Absolute time to advance the scheduler's clock to.
  9646. */
  9647. VirtualTimeSchedulerPrototype.advanceTo = function (time) {
  9648. var dueToClock = this.comparer(this.clock, time);
  9649. if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
  9650. if (dueToClock === 0) { return; }
  9651. if (!this.isEnabled) {
  9652. this.isEnabled = true;
  9653. do {
  9654. var next = this.getNext();
  9655. if (next !== null && this.comparer(next.dueTime, time) <= 0) {
  9656. this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
  9657. next.invoke();
  9658. } else {
  9659. this.isEnabled = false;
  9660. }
  9661. } while (this.isEnabled);
  9662. this.clock = time;
  9663. }
  9664. };
  9665. /**
  9666. * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
  9667. * @param {Number} time Relative time to advance the scheduler's clock by.
  9668. */
  9669. VirtualTimeSchedulerPrototype.advanceBy = function (time) {
  9670. var dt = this.add(this.clock, time),
  9671. dueToClock = this.comparer(this.clock, dt);
  9672. if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
  9673. if (dueToClock === 0) { return; }
  9674. this.advanceTo(dt);
  9675. };
  9676. /**
  9677. * Advances the scheduler's clock by the specified relative time.
  9678. * @param {Number} time Relative time to advance the scheduler's clock by.
  9679. */
  9680. VirtualTimeSchedulerPrototype.sleep = function (time) {
  9681. var dt = this.add(this.clock, time);
  9682. if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
  9683. this.clock = dt;
  9684. };
  9685. /**
  9686. * Gets the next scheduled item to be executed.
  9687. * @returns {ScheduledItem} The next scheduled item.
  9688. */
  9689. VirtualTimeSchedulerPrototype.getNext = function () {
  9690. while (this.queue.length > 0) {
  9691. var next = this.queue.peek();
  9692. if (next.isCancelled()) {
  9693. this.queue.dequeue();
  9694. } else {
  9695. return next;
  9696. }
  9697. }
  9698. return null;
  9699. };
  9700. /**
  9701. * Schedules an action to be executed at dueTime.
  9702. * @param {Mixed} state State passed to the action to be executed.
  9703. * @param {Number} dueTime Absolute time at which to execute the action.
  9704. * @param {Function} action Action to be executed.
  9705. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  9706. */
  9707. VirtualTimeSchedulerPrototype.scheduleAbsolute = function (state, dueTime, action) {
  9708. var self = this;
  9709. function run(scheduler, state1) {
  9710. self.queue.remove(si);
  9711. return action(scheduler, state1);
  9712. }
  9713. var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
  9714. this.queue.enqueue(si);
  9715. return si.disposable;
  9716. };
  9717. return VirtualTimeScheduler;
  9718. }(Scheduler));
  9719. /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
  9720. Rx.HistoricalScheduler = (function (__super__) {
  9721. inherits(HistoricalScheduler, __super__);
  9722. /**
  9723. * Creates a new historical scheduler with the specified initial clock value.
  9724. * @constructor
  9725. * @param {Number} initialClock Initial value for the clock.
  9726. * @param {Function} comparer Comparer to determine causality of events based on absolute time.
  9727. */
  9728. function HistoricalScheduler(initialClock, comparer) {
  9729. var clock = initialClock == null ? 0 : initialClock;
  9730. var cmp = comparer || defaultSubComparer;
  9731. __super__.call(this, clock, cmp);
  9732. }
  9733. var HistoricalSchedulerProto = HistoricalScheduler.prototype;
  9734. /**
  9735. * Adds a relative time value to an absolute time value.
  9736. * @param {Number} absolute Absolute virtual time value.
  9737. * @param {Number} relative Relative virtual time value to add.
  9738. * @return {Number} Resulting absolute virtual time sum value.
  9739. */
  9740. HistoricalSchedulerProto.add = function (absolute, relative) {
  9741. return absolute + relative;
  9742. };
  9743. HistoricalSchedulerProto.toAbsoluteTime = function (absolute) {
  9744. return new Date(absolute).getTime();
  9745. };
  9746. /**
  9747. * Converts the TimeSpan value to a relative virtual time value.
  9748. * @memberOf HistoricalScheduler
  9749. * @param {Number} timeSpan TimeSpan value to convert.
  9750. * @return {Number} Corresponding relative virtual time value.
  9751. */
  9752. HistoricalSchedulerProto.toRelativeTime = function (timeSpan) {
  9753. return timeSpan;
  9754. };
  9755. return HistoricalScheduler;
  9756. }(Rx.VirtualTimeScheduler));
  9757. function OnNextPredicate(predicate) {
  9758. this.predicate = predicate;
  9759. }
  9760. OnNextPredicate.prototype.equals = function (other) {
  9761. if (other === this) { return true; }
  9762. if (other == null) { return false; }
  9763. if (other.kind !== 'N') { return false; }
  9764. return this.predicate(other.value);
  9765. };
  9766. function OnErrorPredicate(predicate) {
  9767. this.predicate = predicate;
  9768. }
  9769. OnErrorPredicate.prototype.equals = function (other) {
  9770. if (other === this) { return true; }
  9771. if (other == null) { return false; }
  9772. if (other.kind !== 'E') { return false; }
  9773. return this.predicate(other.error);
  9774. };
  9775. var ReactiveTest = Rx.ReactiveTest = {
  9776. /** Default virtual time used for creation of observable sequences in unit tests. */
  9777. created: 100,
  9778. /** Default virtual time used to subscribe to observable sequences in unit tests. */
  9779. subscribed: 200,
  9780. /** Default virtual time used to dispose subscriptions in unit tests. */
  9781. disposed: 1000,
  9782. /**
  9783. * Factory method for an OnNext notification record at a given time with a given value or a predicate function.
  9784. *
  9785. * 1 - ReactiveTest.onNext(200, 42);
  9786. * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; });
  9787. *
  9788. * @param ticks Recorded virtual time the OnNext notification occurs.
  9789. * @param value Recorded value stored in the OnNext notification or a predicate.
  9790. * @return Recorded OnNext notification.
  9791. */
  9792. onNext: function (ticks, value) {
  9793. return typeof value === 'function' ?
  9794. new Recorded(ticks, new OnNextPredicate(value)) :
  9795. new Recorded(ticks, Notification.createOnNext(value));
  9796. },
  9797. /**
  9798. * Factory method for an OnError notification record at a given time with a given error.
  9799. *
  9800. * 1 - ReactiveTest.onNext(200, new Error('error'));
  9801. * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; });
  9802. *
  9803. * @param ticks Recorded virtual time the OnError notification occurs.
  9804. * @param exception Recorded exception stored in the OnError notification.
  9805. * @return Recorded OnError notification.
  9806. */
  9807. onError: function (ticks, error) {
  9808. return typeof error === 'function' ?
  9809. new Recorded(ticks, new OnErrorPredicate(error)) :
  9810. new Recorded(ticks, Notification.createOnError(error));
  9811. },
  9812. /**
  9813. * Factory method for an OnCompleted notification record at a given time.
  9814. *
  9815. * @param ticks Recorded virtual time the OnCompleted notification occurs.
  9816. * @return Recorded OnCompleted notification.
  9817. */
  9818. onCompleted: function (ticks) {
  9819. return new Recorded(ticks, Notification.createOnCompleted());
  9820. },
  9821. /**
  9822. * Factory method for a subscription record based on a given subscription and disposal time.
  9823. *
  9824. * @param start Virtual time indicating when the subscription was created.
  9825. * @param end Virtual time indicating when the subscription was disposed.
  9826. * @return Subscription object.
  9827. */
  9828. subscribe: function (start, end) {
  9829. return new Subscription(start, end);
  9830. }
  9831. };
  9832. /**
  9833. * Creates a new object recording the production of the specified value at the given virtual time.
  9834. *
  9835. * @constructor
  9836. * @param {Number} time Virtual time the value was produced on.
  9837. * @param {Mixed} value Value that was produced.
  9838. * @param {Function} comparer An optional comparer.
  9839. */
  9840. var Recorded = Rx.Recorded = function (time, value, comparer) {
  9841. this.time = time;
  9842. this.value = value;
  9843. this.comparer = comparer || defaultComparer;
  9844. };
  9845. /**
  9846. * Checks whether the given recorded object is equal to the current instance.
  9847. *
  9848. * @param {Recorded} other Recorded object to check for equality.
  9849. * @returns {Boolean} true if both objects are equal; false otherwise.
  9850. */
  9851. Recorded.prototype.equals = function (other) {
  9852. return this.time === other.time && this.comparer(this.value, other.value);
  9853. };
  9854. /**
  9855. * Returns a string representation of the current Recorded value.
  9856. *
  9857. * @returns {String} String representation of the current Recorded value.
  9858. */
  9859. Recorded.prototype.toString = function () {
  9860. return this.value.toString() + '@' + this.time;
  9861. };
  9862. /**
  9863. * Creates a new subscription object with the given virtual subscription and unsubscription time.
  9864. *
  9865. * @constructor
  9866. * @param {Number} subscribe Virtual time at which the subscription occurred.
  9867. * @param {Number} unsubscribe Virtual time at which the unsubscription occurred.
  9868. */
  9869. var Subscription = Rx.Subscription = function (start, end) {
  9870. this.subscribe = start;
  9871. this.unsubscribe = end || Number.MAX_VALUE;
  9872. };
  9873. /**
  9874. * Checks whether the given subscription is equal to the current instance.
  9875. * @param other Subscription object to check for equality.
  9876. * @returns {Boolean} true if both objects are equal; false otherwise.
  9877. */
  9878. Subscription.prototype.equals = function (other) {
  9879. return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe;
  9880. };
  9881. /**
  9882. * Returns a string representation of the current Subscription value.
  9883. * @returns {String} String representation of the current Subscription value.
  9884. */
  9885. Subscription.prototype.toString = function () {
  9886. return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')';
  9887. };
  9888. var MockDisposable = Rx.MockDisposable = function (scheduler) {
  9889. this.scheduler = scheduler;
  9890. this.disposes = [];
  9891. this.disposes.push(this.scheduler.clock);
  9892. };
  9893. MockDisposable.prototype.dispose = function () {
  9894. this.disposes.push(this.scheduler.clock);
  9895. };
  9896. var MockObserver = (function (__super__) {
  9897. inherits(MockObserver, __super__);
  9898. function MockObserver(scheduler) {
  9899. __super__.call(this);
  9900. this.scheduler = scheduler;
  9901. this.messages = [];
  9902. }
  9903. var MockObserverPrototype = MockObserver.prototype;
  9904. MockObserverPrototype.onNext = function (value) {
  9905. this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value)));
  9906. };
  9907. MockObserverPrototype.onError = function (e) {
  9908. this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(e)));
  9909. };
  9910. MockObserverPrototype.onCompleted = function () {
  9911. this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted()));
  9912. };
  9913. return MockObserver;
  9914. })(Observer);
  9915. function MockPromise(scheduler, messages) {
  9916. var self = this;
  9917. this.scheduler = scheduler;
  9918. this.messages = messages;
  9919. this.subscriptions = [];
  9920. this.observers = [];
  9921. for (var i = 0, len = this.messages.length; i < len; i++) {
  9922. var message = this.messages[i],
  9923. notification = message.value;
  9924. (function (innerNotification) {
  9925. scheduler.scheduleAbsolute(null, message.time, function () {
  9926. var obs = self.observers.slice(0);
  9927. for (var j = 0, jLen = obs.length; j < jLen; j++) {
  9928. innerNotification.accept(obs[j]);
  9929. }
  9930. return disposableEmpty;
  9931. });
  9932. })(notification);
  9933. }
  9934. }
  9935. MockPromise.prototype.then = function (onResolved, onRejected) {
  9936. var self = this;
  9937. this.subscriptions.push(new Subscription(this.scheduler.clock));
  9938. var index = this.subscriptions.length - 1;
  9939. var newPromise;
  9940. var observer = Rx.Observer.create(
  9941. function (x) {
  9942. var retValue = onResolved(x);
  9943. if (retValue && typeof retValue.then === 'function') {
  9944. newPromise = retValue;
  9945. } else {
  9946. var ticks = self.scheduler.clock;
  9947. newPromise = new MockPromise(self.scheduler, [Rx.ReactiveTest.onNext(ticks, undefined), Rx.ReactiveTest.onCompleted(ticks)]);
  9948. }
  9949. var idx = self.observers.indexOf(observer);
  9950. self.observers.splice(idx, 1);
  9951. self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
  9952. },
  9953. function (err) {
  9954. onRejected(err);
  9955. var idx = self.observers.indexOf(observer);
  9956. self.observers.splice(idx, 1);
  9957. self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
  9958. }
  9959. );
  9960. this.observers.push(observer);
  9961. return newPromise || new MockPromise(this.scheduler, this.messages);
  9962. };
  9963. var HotObservable = (function (__super__) {
  9964. inherits(HotObservable, __super__);
  9965. function HotObservable(scheduler, messages) {
  9966. __super__.call(this);
  9967. var message, notification, observable = this;
  9968. this.scheduler = scheduler;
  9969. this.messages = messages;
  9970. this.subscriptions = [];
  9971. this.observers = [];
  9972. for (var i = 0, len = this.messages.length; i < len; i++) {
  9973. message = this.messages[i];
  9974. notification = message.value;
  9975. (function (innerNotification) {
  9976. scheduler.scheduleAbsolute(null, message.time, function () {
  9977. var obs = observable.observers.slice(0);
  9978. for (var j = 0, jLen = obs.length; j < jLen; j++) {
  9979. innerNotification.accept(obs[j]);
  9980. }
  9981. return disposableEmpty;
  9982. });
  9983. })(notification);
  9984. }
  9985. }
  9986. HotObservable.prototype._subscribe = function (o) {
  9987. var observable = this;
  9988. this.observers.push(o);
  9989. this.subscriptions.push(new Subscription(this.scheduler.clock));
  9990. var index = this.subscriptions.length - 1;
  9991. return disposableCreate(function () {
  9992. var idx = observable.observers.indexOf(o);
  9993. observable.observers.splice(idx, 1);
  9994. observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
  9995. });
  9996. };
  9997. return HotObservable;
  9998. })(Observable);
  9999. var ColdObservable = (function (__super__) {
  10000. inherits(ColdObservable, __super__);
  10001. function ColdObservable(scheduler, messages) {
  10002. __super__.call(this);
  10003. this.scheduler = scheduler;
  10004. this.messages = messages;
  10005. this.subscriptions = [];
  10006. }
  10007. ColdObservable.prototype._subscribe = function (o) {
  10008. var message, notification, observable = this;
  10009. this.subscriptions.push(new Subscription(this.scheduler.clock));
  10010. var index = this.subscriptions.length - 1;
  10011. var d = new CompositeDisposable();
  10012. for (var i = 0, len = this.messages.length; i < len; i++) {
  10013. message = this.messages[i];
  10014. notification = message.value;
  10015. (function (innerNotification) {
  10016. d.add(observable.scheduler.scheduleRelative(null, message.time, function () {
  10017. innerNotification.accept(o);
  10018. return disposableEmpty;
  10019. }));
  10020. })(notification);
  10021. }
  10022. return disposableCreate(function () {
  10023. observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
  10024. d.dispose();
  10025. });
  10026. };
  10027. return ColdObservable;
  10028. })(Observable);
  10029. /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */
  10030. Rx.TestScheduler = (function (__super__) {
  10031. inherits(TestScheduler, __super__);
  10032. function baseComparer(x, y) {
  10033. return x > y ? 1 : (x < y ? -1 : 0);
  10034. }
  10035. function TestScheduler() {
  10036. __super__.call(this, 0, baseComparer);
  10037. }
  10038. /**
  10039. * Schedules an action to be executed at the specified virtual time.
  10040. *
  10041. * @param state State passed to the action to be executed.
  10042. * @param dueTime Absolute virtual time at which to execute the action.
  10043. * @param action Action to be executed.
  10044. * @return Disposable object used to cancel the scheduled action (best effort).
  10045. */
  10046. TestScheduler.prototype.scheduleAbsolute = function (state, dueTime, action) {
  10047. dueTime <= this.clock && (dueTime = this.clock + 1);
  10048. return __super__.prototype.scheduleAbsolute.call(this, state, dueTime, action);
  10049. };
  10050. /**
  10051. * Adds a relative virtual time to an absolute virtual time value.
  10052. *
  10053. * @param absolute Absolute virtual time value.
  10054. * @param relative Relative virtual time value to add.
  10055. * @return Resulting absolute virtual time sum value.
  10056. */
  10057. TestScheduler.prototype.add = function (absolute, relative) {
  10058. return absolute + relative;
  10059. };
  10060. /**
  10061. * Converts the absolute virtual time value to a DateTimeOffset value.
  10062. *
  10063. * @param absolute Absolute virtual time value to convert.
  10064. * @return Corresponding DateTimeOffset value.
  10065. */
  10066. TestScheduler.prototype.toAbsoluteTime = function (absolute) {
  10067. return new Date(absolute).getTime();
  10068. };
  10069. /**
  10070. * Converts the TimeSpan value to a relative virtual time value.
  10071. *
  10072. * @param timeSpan TimeSpan value to convert.
  10073. * @return Corresponding relative virtual time value.
  10074. */
  10075. TestScheduler.prototype.toRelativeTime = function (timeSpan) {
  10076. return timeSpan;
  10077. };
  10078. /**
  10079. * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription.
  10080. *
  10081. * @param create Factory method to create an observable sequence.
  10082. * @param created Virtual time at which to invoke the factory to create an observable sequence.
  10083. * @param subscribed Virtual time at which to subscribe to the created observable sequence.
  10084. * @param disposed Virtual time at which to dispose the subscription.
  10085. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active.
  10086. */
  10087. TestScheduler.prototype.startScheduler = function (createFn, settings) {
  10088. settings || (settings = {});
  10089. settings.created == null && (settings.created = ReactiveTest.created);
  10090. settings.subscribed == null && (settings.subscribed = ReactiveTest.subscribed);
  10091. settings.disposed == null && (settings.disposed = ReactiveTest.disposed);
  10092. var observer = this.createObserver(), source, subscription;
  10093. this.scheduleAbsolute(null, settings.created, function () {
  10094. source = createFn();
  10095. return disposableEmpty;
  10096. });
  10097. this.scheduleAbsolute(null, settings.subscribed, function () {
  10098. subscription = source.subscribe(observer);
  10099. return disposableEmpty;
  10100. });
  10101. this.scheduleAbsolute(null, settings.disposed, function () {
  10102. subscription.dispose();
  10103. return disposableEmpty;
  10104. });
  10105. this.start();
  10106. return observer;
  10107. };
  10108. /**
  10109. * Creates a hot observable using the specified timestamped notification messages either as an array or arguments.
  10110. * @param messages Notifications to surface through the created sequence at their specified absolute virtual times.
  10111. * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications.
  10112. */
  10113. TestScheduler.prototype.createHotObservable = function () {
  10114. var len = arguments.length, args;
  10115. if (Array.isArray(arguments[0])) {
  10116. args = arguments[0];
  10117. } else {
  10118. args = new Array(len);
  10119. for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
  10120. }
  10121. return new HotObservable(this, args);
  10122. };
  10123. /**
  10124. * Creates a cold observable using the specified timestamped notification messages either as an array or arguments.
  10125. * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time.
  10126. * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications.
  10127. */
  10128. TestScheduler.prototype.createColdObservable = function () {
  10129. var len = arguments.length, args;
  10130. if (Array.isArray(arguments[0])) {
  10131. args = arguments[0];
  10132. } else {
  10133. args = new Array(len);
  10134. for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
  10135. }
  10136. return new ColdObservable(this, args);
  10137. };
  10138. /**
  10139. * Creates a resolved promise with the given value and ticks
  10140. * @param {Number} ticks The absolute time of the resolution.
  10141. * @param {Any} value The value to yield at the given tick.
  10142. * @returns {MockPromise} A mock Promise which fulfills with the given value.
  10143. */
  10144. TestScheduler.prototype.createResolvedPromise = function (ticks, value) {
  10145. return new MockPromise(this, [Rx.ReactiveTest.onNext(ticks, value), Rx.ReactiveTest.onCompleted(ticks)]);
  10146. };
  10147. /**
  10148. * Creates a rejected promise with the given reason and ticks
  10149. * @param {Number} ticks The absolute time of the resolution.
  10150. * @param {Any} reason The reason for rejection to yield at the given tick.
  10151. * @returns {MockPromise} A mock Promise which rejects with the given reason.
  10152. */
  10153. TestScheduler.prototype.createRejectedPromise = function (ticks, reason) {
  10154. return new MockPromise(this, [Rx.ReactiveTest.onError(ticks, reason)]);
  10155. };
  10156. /**
  10157. * Creates an observer that records received notification messages and timestamps those.
  10158. * @return Observer that can be used to assert the timing of received notifications.
  10159. */
  10160. TestScheduler.prototype.createObserver = function () {
  10161. return new MockObserver(this);
  10162. };
  10163. return TestScheduler;
  10164. })(VirtualTimeScheduler);
  10165. var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
  10166. inherits(AnonymousObservable, __super__);
  10167. // Fix subscriber to check for undefined or function returned to decorate as Disposable
  10168. function fixSubscriber(subscriber) {
  10169. return subscriber && isFunction(subscriber.dispose) ? subscriber :
  10170. isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
  10171. }
  10172. function setDisposable(s, state) {
  10173. var ado = state[0], self = state[1];
  10174. var sub = tryCatch(self.__subscribe).call(self, ado);
  10175. if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
  10176. ado.setDisposable(fixSubscriber(sub));
  10177. }
  10178. function AnonymousObservable(subscribe, parent) {
  10179. this.source = parent;
  10180. this.__subscribe = subscribe;
  10181. __super__.call(this);
  10182. }
  10183. AnonymousObservable.prototype._subscribe = function (o) {
  10184. var ado = new AutoDetachObserver(o), state = [ado, this];
  10185. if (currentThreadScheduler.scheduleRequired()) {
  10186. currentThreadScheduler.schedule(state, setDisposable);
  10187. } else {
  10188. setDisposable(null, state);
  10189. }
  10190. return ado;
  10191. };
  10192. return AnonymousObservable;
  10193. }(Observable));
  10194. var AutoDetachObserver = (function (__super__) {
  10195. inherits(AutoDetachObserver, __super__);
  10196. function AutoDetachObserver(observer) {
  10197. __super__.call(this);
  10198. this.observer = observer;
  10199. this.m = new SingleAssignmentDisposable();
  10200. }
  10201. var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
  10202. AutoDetachObserverPrototype.next = function (value) {
  10203. var result = tryCatch(this.observer.onNext).call(this.observer, value);
  10204. if (result === errorObj) {
  10205. this.dispose();
  10206. thrower(result.e);
  10207. }
  10208. };
  10209. AutoDetachObserverPrototype.error = function (err) {
  10210. var result = tryCatch(this.observer.onError).call(this.observer, err);
  10211. this.dispose();
  10212. result === errorObj && thrower(result.e);
  10213. };
  10214. AutoDetachObserverPrototype.completed = function () {
  10215. var result = tryCatch(this.observer.onCompleted).call(this.observer);
  10216. this.dispose();
  10217. result === errorObj && thrower(result.e);
  10218. };
  10219. AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
  10220. AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
  10221. AutoDetachObserverPrototype.dispose = function () {
  10222. __super__.prototype.dispose.call(this);
  10223. this.m.dispose();
  10224. };
  10225. return AutoDetachObserver;
  10226. }(AbstractObserver));
  10227. var UnderlyingObservable = (function (__super__) {
  10228. inherits(UnderlyingObservable, __super__);
  10229. function UnderlyingObservable(m, u) {
  10230. this._m = m;
  10231. this._u = u;
  10232. __super__.call(this);
  10233. }
  10234. UnderlyingObservable.prototype.subscribeCore = function (o) {
  10235. return new BinaryDisposable(this._m.getDisposable(), this._u.subscribe(o));
  10236. };
  10237. return UnderlyingObservable;
  10238. }(ObservableBase));
  10239. var GroupedObservable = (function (__super__) {
  10240. inherits(GroupedObservable, __super__);
  10241. function GroupedObservable(key, underlyingObservable, mergedDisposable) {
  10242. __super__.call(this);
  10243. this.key = key;
  10244. this.underlyingObservable = !mergedDisposable ?
  10245. underlyingObservable :
  10246. new UnderlyingObservable(mergedDisposable, underlyingObservable);
  10247. }
  10248. GroupedObservable.prototype._subscribe = function (o) {
  10249. return this.underlyingObservable.subscribe(o);
  10250. };
  10251. return GroupedObservable;
  10252. }(Observable));
  10253. /**
  10254. * Represents an object that is both an observable sequence as well as an observer.
  10255. * Each notification is broadcasted to all subscribed observers.
  10256. */
  10257. var Subject = Rx.Subject = (function (__super__) {
  10258. inherits(Subject, __super__);
  10259. function Subject() {
  10260. __super__.call(this);
  10261. this.isDisposed = false;
  10262. this.isStopped = false;
  10263. this.observers = [];
  10264. this.hasError = false;
  10265. }
  10266. addProperties(Subject.prototype, Observer.prototype, {
  10267. _subscribe: function (o) {
  10268. checkDisposed(this);
  10269. if (!this.isStopped) {
  10270. this.observers.push(o);
  10271. return new InnerSubscription(this, o);
  10272. }
  10273. if (this.hasError) {
  10274. o.onError(this.error);
  10275. return disposableEmpty;
  10276. }
  10277. o.onCompleted();
  10278. return disposableEmpty;
  10279. },
  10280. /**
  10281. * Indicates whether the subject has observers subscribed to it.
  10282. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  10283. */
  10284. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  10285. /**
  10286. * Notifies all subscribed observers about the end of the sequence.
  10287. */
  10288. onCompleted: function () {
  10289. checkDisposed(this);
  10290. if (!this.isStopped) {
  10291. this.isStopped = true;
  10292. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10293. os[i].onCompleted();
  10294. }
  10295. this.observers.length = 0;
  10296. }
  10297. },
  10298. /**
  10299. * Notifies all subscribed observers about the exception.
  10300. * @param {Mixed} error The exception to send to all observers.
  10301. */
  10302. onError: function (error) {
  10303. checkDisposed(this);
  10304. if (!this.isStopped) {
  10305. this.isStopped = true;
  10306. this.error = error;
  10307. this.hasError = true;
  10308. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10309. os[i].onError(error);
  10310. }
  10311. this.observers.length = 0;
  10312. }
  10313. },
  10314. /**
  10315. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  10316. * @param {Mixed} value The value to send to all observers.
  10317. */
  10318. onNext: function (value) {
  10319. checkDisposed(this);
  10320. if (!this.isStopped) {
  10321. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10322. os[i].onNext(value);
  10323. }
  10324. }
  10325. },
  10326. /**
  10327. * Unsubscribe all observers and release resources.
  10328. */
  10329. dispose: function () {
  10330. this.isDisposed = true;
  10331. this.observers = null;
  10332. }
  10333. });
  10334. /**
  10335. * Creates a subject from the specified observer and observable.
  10336. * @param {Observer} observer The observer used to send messages to the subject.
  10337. * @param {Observable} observable The observable used to subscribe to messages sent from the subject.
  10338. * @returns {Subject} Subject implemented using the given observer and observable.
  10339. */
  10340. Subject.create = function (observer, observable) {
  10341. return new AnonymousSubject(observer, observable);
  10342. };
  10343. return Subject;
  10344. }(Observable));
  10345. /**
  10346. * Represents the result of an asynchronous operation.
  10347. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
  10348. */
  10349. var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
  10350. inherits(AsyncSubject, __super__);
  10351. /**
  10352. * Creates a subject that can only receive one value and that value is cached for all future observations.
  10353. * @constructor
  10354. */
  10355. function AsyncSubject() {
  10356. __super__.call(this);
  10357. this.isDisposed = false;
  10358. this.isStopped = false;
  10359. this.hasValue = false;
  10360. this.observers = [];
  10361. this.hasError = false;
  10362. }
  10363. addProperties(AsyncSubject.prototype, Observer.prototype, {
  10364. _subscribe: function (o) {
  10365. checkDisposed(this);
  10366. if (!this.isStopped) {
  10367. this.observers.push(o);
  10368. return new InnerSubscription(this, o);
  10369. }
  10370. if (this.hasError) {
  10371. o.onError(this.error);
  10372. } else if (this.hasValue) {
  10373. o.onNext(this.value);
  10374. o.onCompleted();
  10375. } else {
  10376. o.onCompleted();
  10377. }
  10378. return disposableEmpty;
  10379. },
  10380. /**
  10381. * Indicates whether the subject has observers subscribed to it.
  10382. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  10383. */
  10384. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  10385. /**
  10386. * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
  10387. */
  10388. onCompleted: function () {
  10389. var i, len;
  10390. checkDisposed(this);
  10391. if (!this.isStopped) {
  10392. this.isStopped = true;
  10393. var os = cloneArray(this.observers), len = os.length;
  10394. if (this.hasValue) {
  10395. for (i = 0; i < len; i++) {
  10396. var o = os[i];
  10397. o.onNext(this.value);
  10398. o.onCompleted();
  10399. }
  10400. } else {
  10401. for (i = 0; i < len; i++) {
  10402. os[i].onCompleted();
  10403. }
  10404. }
  10405. this.observers.length = 0;
  10406. }
  10407. },
  10408. /**
  10409. * Notifies all subscribed observers about the error.
  10410. * @param {Mixed} error The Error to send to all observers.
  10411. */
  10412. onError: function (error) {
  10413. checkDisposed(this);
  10414. if (!this.isStopped) {
  10415. this.isStopped = true;
  10416. this.hasError = true;
  10417. this.error = error;
  10418. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10419. os[i].onError(error);
  10420. }
  10421. this.observers.length = 0;
  10422. }
  10423. },
  10424. /**
  10425. * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
  10426. * @param {Mixed} value The value to store in the subject.
  10427. */
  10428. onNext: function (value) {
  10429. checkDisposed(this);
  10430. if (this.isStopped) { return; }
  10431. this.value = value;
  10432. this.hasValue = true;
  10433. },
  10434. /**
  10435. * Unsubscribe all observers and release resources.
  10436. */
  10437. dispose: function () {
  10438. this.isDisposed = true;
  10439. this.observers = null;
  10440. this.error = null;
  10441. this.value = null;
  10442. }
  10443. });
  10444. return AsyncSubject;
  10445. }(Observable));
  10446. /**
  10447. * Represents a value that changes over time.
  10448. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
  10449. */
  10450. var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
  10451. inherits(BehaviorSubject, __super__);
  10452. function BehaviorSubject(value) {
  10453. __super__.call(this);
  10454. this.value = value;
  10455. this.observers = [];
  10456. this.isDisposed = false;
  10457. this.isStopped = false;
  10458. this.hasError = false;
  10459. }
  10460. addProperties(BehaviorSubject.prototype, Observer.prototype, {
  10461. _subscribe: function (o) {
  10462. checkDisposed(this);
  10463. if (!this.isStopped) {
  10464. this.observers.push(o);
  10465. o.onNext(this.value);
  10466. return new InnerSubscription(this, o);
  10467. }
  10468. if (this.hasError) {
  10469. o.onError(this.error);
  10470. } else {
  10471. o.onCompleted();
  10472. }
  10473. return disposableEmpty;
  10474. },
  10475. /**
  10476. * Gets the current value or throws an exception.
  10477. * Value is frozen after onCompleted is called.
  10478. * After onError is called always throws the specified exception.
  10479. * An exception is always thrown after dispose is called.
  10480. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
  10481. */
  10482. getValue: function () {
  10483. checkDisposed(this);
  10484. if (this.hasError) { thrower(this.error); }
  10485. return this.value;
  10486. },
  10487. /**
  10488. * Indicates whether the subject has observers subscribed to it.
  10489. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  10490. */
  10491. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  10492. /**
  10493. * Notifies all subscribed observers about the end of the sequence.
  10494. */
  10495. onCompleted: function () {
  10496. checkDisposed(this);
  10497. if (this.isStopped) { return; }
  10498. this.isStopped = true;
  10499. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10500. os[i].onCompleted();
  10501. }
  10502. this.observers.length = 0;
  10503. },
  10504. /**
  10505. * Notifies all subscribed observers about the exception.
  10506. * @param {Mixed} error The exception to send to all observers.
  10507. */
  10508. onError: function (error) {
  10509. checkDisposed(this);
  10510. if (this.isStopped) { return; }
  10511. this.isStopped = true;
  10512. this.hasError = true;
  10513. this.error = error;
  10514. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10515. os[i].onError(error);
  10516. }
  10517. this.observers.length = 0;
  10518. },
  10519. /**
  10520. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  10521. * @param {Mixed} value The value to send to all observers.
  10522. */
  10523. onNext: function (value) {
  10524. checkDisposed(this);
  10525. if (this.isStopped) { return; }
  10526. this.value = value;
  10527. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10528. os[i].onNext(value);
  10529. }
  10530. },
  10531. /**
  10532. * Unsubscribe all observers and release resources.
  10533. */
  10534. dispose: function () {
  10535. this.isDisposed = true;
  10536. this.observers = null;
  10537. this.value = null;
  10538. this.error = null;
  10539. }
  10540. });
  10541. return BehaviorSubject;
  10542. }(Observable));
  10543. /**
  10544. * Represents an object that is both an observable sequence as well as an observer.
  10545. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
  10546. */
  10547. var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
  10548. var maxSafeInteger = Math.pow(2, 53) - 1;
  10549. function createRemovableDisposable(subject, observer) {
  10550. return disposableCreate(function () {
  10551. observer.dispose();
  10552. !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
  10553. });
  10554. }
  10555. inherits(ReplaySubject, __super__);
  10556. /**
  10557. * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
  10558. * @param {Number} [bufferSize] Maximum element count of the replay buffer.
  10559. * @param {Number} [windowSize] Maximum time length of the replay buffer.
  10560. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
  10561. */
  10562. function ReplaySubject(bufferSize, windowSize, scheduler) {
  10563. this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
  10564. this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
  10565. this.scheduler = scheduler || currentThreadScheduler;
  10566. this.q = [];
  10567. this.observers = [];
  10568. this.isStopped = false;
  10569. this.isDisposed = false;
  10570. this.hasError = false;
  10571. this.error = null;
  10572. __super__.call(this);
  10573. }
  10574. addProperties(ReplaySubject.prototype, Observer.prototype, {
  10575. _subscribe: function (o) {
  10576. checkDisposed(this);
  10577. var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so);
  10578. this._trim(this.scheduler.now());
  10579. this.observers.push(so);
  10580. for (var i = 0, len = this.q.length; i < len; i++) {
  10581. so.onNext(this.q[i].value);
  10582. }
  10583. if (this.hasError) {
  10584. so.onError(this.error);
  10585. } else if (this.isStopped) {
  10586. so.onCompleted();
  10587. }
  10588. so.ensureActive();
  10589. return subscription;
  10590. },
  10591. /**
  10592. * Indicates whether the subject has observers subscribed to it.
  10593. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  10594. */
  10595. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  10596. _trim: function (now) {
  10597. while (this.q.length > this.bufferSize) {
  10598. this.q.shift();
  10599. }
  10600. while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
  10601. this.q.shift();
  10602. }
  10603. },
  10604. /**
  10605. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  10606. * @param {Mixed} value The value to send to all observers.
  10607. */
  10608. onNext: function (value) {
  10609. checkDisposed(this);
  10610. if (this.isStopped) { return; }
  10611. var now = this.scheduler.now();
  10612. this.q.push({ interval: now, value: value });
  10613. this._trim(now);
  10614. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10615. var observer = os[i];
  10616. observer.onNext(value);
  10617. observer.ensureActive();
  10618. }
  10619. },
  10620. /**
  10621. * Notifies all subscribed observers about the exception.
  10622. * @param {Mixed} error The exception to send to all observers.
  10623. */
  10624. onError: function (error) {
  10625. checkDisposed(this);
  10626. if (this.isStopped) { return; }
  10627. this.isStopped = true;
  10628. this.error = error;
  10629. this.hasError = true;
  10630. var now = this.scheduler.now();
  10631. this._trim(now);
  10632. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10633. var observer = os[i];
  10634. observer.onError(error);
  10635. observer.ensureActive();
  10636. }
  10637. this.observers.length = 0;
  10638. },
  10639. /**
  10640. * Notifies all subscribed observers about the end of the sequence.
  10641. */
  10642. onCompleted: function () {
  10643. checkDisposed(this);
  10644. if (this.isStopped) { return; }
  10645. this.isStopped = true;
  10646. var now = this.scheduler.now();
  10647. this._trim(now);
  10648. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  10649. var observer = os[i];
  10650. observer.onCompleted();
  10651. observer.ensureActive();
  10652. }
  10653. this.observers.length = 0;
  10654. },
  10655. /**
  10656. * Unsubscribe all observers and release resources.
  10657. */
  10658. dispose: function () {
  10659. this.isDisposed = true;
  10660. this.observers = null;
  10661. }
  10662. });
  10663. return ReplaySubject;
  10664. }(Observable));
  10665. var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
  10666. inherits(AnonymousSubject, __super__);
  10667. function AnonymousSubject(observer, observable) {
  10668. this.observer = observer;
  10669. this.observable = observable;
  10670. __super__.call(this);
  10671. }
  10672. addProperties(AnonymousSubject.prototype, Observer.prototype, {
  10673. _subscribe: function (o) {
  10674. return this.observable.subscribe(o);
  10675. },
  10676. onCompleted: function () {
  10677. this.observer.onCompleted();
  10678. },
  10679. onError: function (error) {
  10680. this.observer.onError(error);
  10681. },
  10682. onNext: function (value) {
  10683. this.observer.onNext(value);
  10684. }
  10685. });
  10686. return AnonymousSubject;
  10687. }(Observable));
  10688. /**
  10689. * Used to pause and resume streams.
  10690. */
  10691. Rx.Pauser = (function (__super__) {
  10692. inherits(Pauser, __super__);
  10693. function Pauser() {
  10694. __super__.call(this);
  10695. }
  10696. /**
  10697. * Pauses the underlying sequence.
  10698. */
  10699. Pauser.prototype.pause = function () { this.onNext(false); };
  10700. /**
  10701. * Resumes the underlying sequence.
  10702. */
  10703. Pauser.prototype.resume = function () { this.onNext(true); };
  10704. return Pauser;
  10705. }(Subject));
  10706. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  10707. root.Rx = Rx;
  10708. define(function() {
  10709. return Rx;
  10710. });
  10711. } else if (freeExports && freeModule) {
  10712. // in Node.js or RingoJS
  10713. if (moduleExports) {
  10714. (freeModule.exports = Rx).Rx = Rx;
  10715. } else {
  10716. freeExports.Rx = Rx;
  10717. }
  10718. } else {
  10719. // in a browser or Rhino
  10720. root.Rx = Rx;
  10721. }
  10722. // All code before this point will be filtered from stack traces.
  10723. var rEndingLine = captureLine();
  10724. }.call(this));