Front end of the Slack clone application.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055
  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) {
  47. var len = arr.length, a = new Array(len);
  48. for(var i = 0; i < len; i++) { a[i] = arr[i]; }
  49. return a;
  50. }
  51. var errorObj = {e: {}};
  52. function tryCatcherGen(tryCatchTarget) {
  53. return function tryCatcher() {
  54. try {
  55. return tryCatchTarget.apply(this, arguments);
  56. } catch (e) {
  57. errorObj.e = e;
  58. return errorObj;
  59. }
  60. };
  61. }
  62. var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
  63. if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
  64. return tryCatcherGen(fn);
  65. };
  66. function thrower(e) {
  67. throw e;
  68. }
  69. Rx.config.longStackSupport = false;
  70. var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })();
  71. hasStacks = !!stacks.e && !!stacks.e.stack;
  72. // All code after this point will be filtered from stack traces reported by RxJS
  73. var rStartingLine = captureLine(), rFileName;
  74. var STACK_JUMP_SEPARATOR = 'From previous event:';
  75. function makeStackTraceLong(error, observable) {
  76. // If possible, transform the error stack trace by removing Node and RxJS
  77. // cruft, then concatenating with the stack trace of `observable`.
  78. if (hasStacks &&
  79. observable.stack &&
  80. typeof error === 'object' &&
  81. error !== null &&
  82. error.stack &&
  83. error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
  84. ) {
  85. var stacks = [];
  86. for (var o = observable; !!o; o = o.source) {
  87. if (o.stack) {
  88. stacks.unshift(o.stack);
  89. }
  90. }
  91. stacks.unshift(error.stack);
  92. var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n');
  93. error.stack = filterStackString(concatedStacks);
  94. }
  95. }
  96. function filterStackString(stackString) {
  97. var lines = stackString.split('\n'), desiredLines = [];
  98. for (var i = 0, len = lines.length; i < len; i++) {
  99. var line = lines[i];
  100. if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
  101. desiredLines.push(line);
  102. }
  103. }
  104. return desiredLines.join('\n');
  105. }
  106. function isInternalFrame(stackLine) {
  107. var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
  108. if (!fileNameAndLineNumber) {
  109. return false;
  110. }
  111. var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
  112. return fileName === rFileName &&
  113. lineNumber >= rStartingLine &&
  114. lineNumber <= rEndingLine;
  115. }
  116. function isNodeFrame(stackLine) {
  117. return stackLine.indexOf('(module.js:') !== -1 ||
  118. stackLine.indexOf('(node.js:') !== -1;
  119. }
  120. function captureLine() {
  121. if (!hasStacks) { return; }
  122. try {
  123. throw new Error();
  124. } catch (e) {
  125. var lines = e.stack.split('\n');
  126. var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2];
  127. var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
  128. if (!fileNameAndLineNumber) { return; }
  129. rFileName = fileNameAndLineNumber[0];
  130. return fileNameAndLineNumber[1];
  131. }
  132. }
  133. function getFileNameAndLineNumber(stackLine) {
  134. // Named functions: 'at functionName (filename:lineNumber:columnNumber)'
  135. var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
  136. if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
  137. // Anonymous functions: 'at filename:lineNumber:columnNumber'
  138. var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
  139. if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
  140. // Firefox style: 'function@filename:lineNumber or @filename:lineNumber'
  141. var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
  142. if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
  143. }
  144. var EmptyError = Rx.EmptyError = function() {
  145. this.message = 'Sequence contains no elements.';
  146. Error.call(this);
  147. };
  148. EmptyError.prototype = Object.create(Error.prototype);
  149. EmptyError.prototype.name = 'EmptyError';
  150. var ObjectDisposedError = Rx.ObjectDisposedError = function() {
  151. this.message = 'Object has been disposed';
  152. Error.call(this);
  153. };
  154. ObjectDisposedError.prototype = Object.create(Error.prototype);
  155. ObjectDisposedError.prototype.name = 'ObjectDisposedError';
  156. var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
  157. this.message = 'Argument out of range';
  158. Error.call(this);
  159. };
  160. ArgumentOutOfRangeError.prototype = Object.create(Error.prototype);
  161. ArgumentOutOfRangeError.prototype.name = 'ArgumentOutOfRangeError';
  162. var NotSupportedError = Rx.NotSupportedError = function (message) {
  163. this.message = message || 'This operation is not supported';
  164. Error.call(this);
  165. };
  166. NotSupportedError.prototype = Object.create(Error.prototype);
  167. NotSupportedError.prototype.name = 'NotSupportedError';
  168. var NotImplementedError = Rx.NotImplementedError = function (message) {
  169. this.message = message || 'This operation is not implemented';
  170. Error.call(this);
  171. };
  172. NotImplementedError.prototype = Object.create(Error.prototype);
  173. NotImplementedError.prototype.name = 'NotImplementedError';
  174. var notImplemented = Rx.helpers.notImplemented = function () {
  175. throw new NotImplementedError();
  176. };
  177. var notSupported = Rx.helpers.notSupported = function () {
  178. throw new NotSupportedError();
  179. };
  180. // Shim in iterator support
  181. var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
  182. '_es6shim_iterator_';
  183. // Bug for mozilla version
  184. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
  185. $iterator$ = '@@iterator';
  186. }
  187. var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
  188. var isIterable = Rx.helpers.isIterable = function (o) {
  189. return o && o[$iterator$] !== undefined;
  190. };
  191. var isArrayLike = Rx.helpers.isArrayLike = function (o) {
  192. return o && o.length !== undefined;
  193. };
  194. Rx.helpers.iterator = $iterator$;
  195. var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
  196. if (typeof thisArg === 'undefined') { return func; }
  197. switch(argCount) {
  198. case 0:
  199. return function() {
  200. return func.call(thisArg)
  201. };
  202. case 1:
  203. return function(arg) {
  204. return func.call(thisArg, arg);
  205. };
  206. case 2:
  207. return function(value, index) {
  208. return func.call(thisArg, value, index);
  209. };
  210. case 3:
  211. return function(value, index, collection) {
  212. return func.call(thisArg, value, index, collection);
  213. };
  214. }
  215. return function() {
  216. return func.apply(thisArg, arguments);
  217. };
  218. };
  219. /** Used to determine if values are of the language type Object */
  220. var dontEnums = ['toString',
  221. 'toLocaleString',
  222. 'valueOf',
  223. 'hasOwnProperty',
  224. 'isPrototypeOf',
  225. 'propertyIsEnumerable',
  226. 'constructor'],
  227. dontEnumsLength = dontEnums.length;
  228. var argsTag = '[object Arguments]',
  229. arrayTag = '[object Array]',
  230. boolTag = '[object Boolean]',
  231. dateTag = '[object Date]',
  232. errorTag = '[object Error]',
  233. funcTag = '[object Function]',
  234. mapTag = '[object Map]',
  235. numberTag = '[object Number]',
  236. objectTag = '[object Object]',
  237. regexpTag = '[object RegExp]',
  238. setTag = '[object Set]',
  239. stringTag = '[object String]',
  240. weakMapTag = '[object WeakMap]';
  241. var arrayBufferTag = '[object ArrayBuffer]',
  242. float32Tag = '[object Float32Array]',
  243. float64Tag = '[object Float64Array]',
  244. int8Tag = '[object Int8Array]',
  245. int16Tag = '[object Int16Array]',
  246. int32Tag = '[object Int32Array]',
  247. uint8Tag = '[object Uint8Array]',
  248. uint8ClampedTag = '[object Uint8ClampedArray]',
  249. uint16Tag = '[object Uint16Array]',
  250. uint32Tag = '[object Uint32Array]';
  251. var typedArrayTags = {};
  252. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  253. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  254. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  255. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  256. typedArrayTags[uint32Tag] = true;
  257. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  258. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  259. typedArrayTags[dateTag] = typedArrayTags[errorTag] =
  260. typedArrayTags[funcTag] = typedArrayTags[mapTag] =
  261. typedArrayTags[numberTag] = typedArrayTags[objectTag] =
  262. typedArrayTags[regexpTag] = typedArrayTags[setTag] =
  263. typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
  264. var objectProto = Object.prototype,
  265. hasOwnProperty = objectProto.hasOwnProperty,
  266. objToString = objectProto.toString,
  267. MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
  268. var keys = Object.keys || (function() {
  269. var hasOwnProperty = Object.prototype.hasOwnProperty,
  270. hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
  271. dontEnums = [
  272. 'toString',
  273. 'toLocaleString',
  274. 'valueOf',
  275. 'hasOwnProperty',
  276. 'isPrototypeOf',
  277. 'propertyIsEnumerable',
  278. 'constructor'
  279. ],
  280. dontEnumsLength = dontEnums.length;
  281. return function(obj) {
  282. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  283. throw new TypeError('Object.keys called on non-object');
  284. }
  285. var result = [], prop, i;
  286. for (prop in obj) {
  287. if (hasOwnProperty.call(obj, prop)) {
  288. result.push(prop);
  289. }
  290. }
  291. if (hasDontEnumBug) {
  292. for (i = 0; i < dontEnumsLength; i++) {
  293. if (hasOwnProperty.call(obj, dontEnums[i])) {
  294. result.push(dontEnums[i]);
  295. }
  296. }
  297. }
  298. return result;
  299. };
  300. }());
  301. function equalObjects(object, other, equalFunc, isLoose, stackA, stackB) {
  302. var objProps = keys(object),
  303. objLength = objProps.length,
  304. othProps = keys(other),
  305. othLength = othProps.length;
  306. if (objLength !== othLength && !isLoose) {
  307. return false;
  308. }
  309. var index = objLength, key;
  310. while (index--) {
  311. key = objProps[index];
  312. if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
  313. return false;
  314. }
  315. }
  316. var skipCtor = isLoose;
  317. while (++index < objLength) {
  318. key = objProps[index];
  319. var objValue = object[key],
  320. othValue = other[key],
  321. result;
  322. if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) {
  323. return false;
  324. }
  325. skipCtor || (skipCtor = key === 'constructor');
  326. }
  327. if (!skipCtor) {
  328. var objCtor = object.constructor,
  329. othCtor = other.constructor;
  330. if (objCtor !== othCtor &&
  331. ('constructor' in object && 'constructor' in other) &&
  332. !(typeof objCtor === 'function' && objCtor instanceof objCtor &&
  333. typeof othCtor === 'function' && othCtor instanceof othCtor)) {
  334. return false;
  335. }
  336. }
  337. return true;
  338. }
  339. function equalByTag(object, other, tag) {
  340. switch (tag) {
  341. case boolTag:
  342. case dateTag:
  343. return +object === +other;
  344. case errorTag:
  345. return object.name === other.name && object.message === other.message;
  346. case numberTag:
  347. return (object !== +object) ?
  348. other !== +other :
  349. object === +other;
  350. case regexpTag:
  351. case stringTag:
  352. return object === (other + '');
  353. }
  354. return false;
  355. }
  356. var isObject = Rx.internals.isObject = function(value) {
  357. var type = typeof value;
  358. return !!value && (type === 'object' || type === 'function');
  359. };
  360. function isObjectLike(value) {
  361. return !!value && typeof value === 'object';
  362. }
  363. function isLength(value) {
  364. return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
  365. }
  366. var isHostObject = (function() {
  367. try {
  368. Object({ 'toString': 0 } + '');
  369. } catch(e) {
  370. return function() { return false; };
  371. }
  372. return function(value) {
  373. return typeof value.toString !== 'function' && typeof (value + '') === 'string';
  374. };
  375. }());
  376. function isTypedArray(value) {
  377. return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
  378. }
  379. var isArray = Array.isArray || function(value) {
  380. return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag;
  381. };
  382. function arraySome (array, predicate) {
  383. var index = -1,
  384. length = array.length;
  385. while (++index < length) {
  386. if (predicate(array[index], index, array)) {
  387. return true;
  388. }
  389. }
  390. return false;
  391. }
  392. function equalArrays(array, other, equalFunc, isLoose, stackA, stackB) {
  393. var index = -1,
  394. arrLength = array.length,
  395. othLength = other.length;
  396. if (arrLength !== othLength && !(isLoose && othLength > arrLength)) {
  397. return false;
  398. }
  399. // Ignore non-index properties.
  400. while (++index < arrLength) {
  401. var arrValue = array[index],
  402. othValue = other[index],
  403. result;
  404. if (result !== undefined) {
  405. if (result) {
  406. continue;
  407. }
  408. return false;
  409. }
  410. // Recursively compare arrays (susceptible to call stack limits).
  411. if (isLoose) {
  412. if (!arraySome(other, function(othValue) {
  413. return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB);
  414. })) {
  415. return false;
  416. }
  417. } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) {
  418. return false;
  419. }
  420. }
  421. return true;
  422. }
  423. function baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) {
  424. var objIsArr = isArray(object),
  425. othIsArr = isArray(other),
  426. objTag = arrayTag,
  427. othTag = arrayTag;
  428. if (!objIsArr) {
  429. objTag = objToString.call(object);
  430. if (objTag === argsTag) {
  431. objTag = objectTag;
  432. } else if (objTag !== objectTag) {
  433. objIsArr = isTypedArray(object);
  434. }
  435. }
  436. if (!othIsArr) {
  437. othTag = objToString.call(other);
  438. if (othTag === argsTag) {
  439. othTag = objectTag;
  440. }
  441. }
  442. var objIsObj = objTag === objectTag && !isHostObject(object),
  443. othIsObj = othTag === objectTag && !isHostObject(other),
  444. isSameTag = objTag === othTag;
  445. if (isSameTag && !(objIsArr || objIsObj)) {
  446. return equalByTag(object, other, objTag);
  447. }
  448. if (!isLoose) {
  449. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  450. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  451. if (objIsWrapped || othIsWrapped) {
  452. return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB);
  453. }
  454. }
  455. if (!isSameTag) {
  456. return false;
  457. }
  458. // Assume cyclic values are equal.
  459. // For more information on detecting circular references see https://es5.github.io/#JO.
  460. stackA || (stackA = []);
  461. stackB || (stackB = []);
  462. var length = stackA.length;
  463. while (length--) {
  464. if (stackA[length] === object) {
  465. return stackB[length] === other;
  466. }
  467. }
  468. // Add `object` and `other` to the stack of traversed objects.
  469. stackA.push(object);
  470. stackB.push(other);
  471. var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB);
  472. stackA.pop();
  473. stackB.pop();
  474. return result;
  475. }
  476. function baseIsEqual(value, other, isLoose, stackA, stackB) {
  477. if (value === other) {
  478. return true;
  479. }
  480. if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
  481. return value !== value && other !== other;
  482. }
  483. return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB);
  484. }
  485. var isEqual = Rx.internals.isEqual = function (value, other) {
  486. return baseIsEqual(value, other);
  487. };
  488. var hasProp = {}.hasOwnProperty,
  489. slice = Array.prototype.slice;
  490. var inherits = Rx.internals.inherits = function (child, parent) {
  491. function __() { this.constructor = child; }
  492. __.prototype = parent.prototype;
  493. child.prototype = new __();
  494. };
  495. var addProperties = Rx.internals.addProperties = function (obj) {
  496. for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
  497. for (var idx = 0, ln = sources.length; idx < ln; idx++) {
  498. var source = sources[idx];
  499. for (var prop in source) {
  500. obj[prop] = source[prop];
  501. }
  502. }
  503. };
  504. // Rx Utils
  505. var addRef = Rx.internals.addRef = function (xs, r) {
  506. return new AnonymousObservable(function (observer) {
  507. return new BinaryDisposable(r.getDisposable(), xs.subscribe(observer));
  508. });
  509. };
  510. function arrayInitialize(count, factory) {
  511. var a = new Array(count);
  512. for (var i = 0; i < count; i++) {
  513. a[i] = factory();
  514. }
  515. return a;
  516. }
  517. /**
  518. * Represents a group of disposable resources that are disposed together.
  519. * @constructor
  520. */
  521. var CompositeDisposable = Rx.CompositeDisposable = function () {
  522. var args = [], i, len;
  523. if (Array.isArray(arguments[0])) {
  524. args = arguments[0];
  525. } else {
  526. len = arguments.length;
  527. args = new Array(len);
  528. for(i = 0; i < len; i++) { args[i] = arguments[i]; }
  529. }
  530. this.disposables = args;
  531. this.isDisposed = false;
  532. this.length = args.length;
  533. };
  534. var CompositeDisposablePrototype = CompositeDisposable.prototype;
  535. /**
  536. * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
  537. * @param {Mixed} item Disposable to add.
  538. */
  539. CompositeDisposablePrototype.add = function (item) {
  540. if (this.isDisposed) {
  541. item.dispose();
  542. } else {
  543. this.disposables.push(item);
  544. this.length++;
  545. }
  546. };
  547. /**
  548. * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
  549. * @param {Mixed} item Disposable to remove.
  550. * @returns {Boolean} true if found; false otherwise.
  551. */
  552. CompositeDisposablePrototype.remove = function (item) {
  553. var shouldDispose = false;
  554. if (!this.isDisposed) {
  555. var idx = this.disposables.indexOf(item);
  556. if (idx !== -1) {
  557. shouldDispose = true;
  558. this.disposables.splice(idx, 1);
  559. this.length--;
  560. item.dispose();
  561. }
  562. }
  563. return shouldDispose;
  564. };
  565. /**
  566. * Disposes all disposables in the group and removes them from the group.
  567. */
  568. CompositeDisposablePrototype.dispose = function () {
  569. if (!this.isDisposed) {
  570. this.isDisposed = true;
  571. var len = this.disposables.length, currentDisposables = new Array(len);
  572. for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
  573. this.disposables = [];
  574. this.length = 0;
  575. for (i = 0; i < len; i++) {
  576. currentDisposables[i].dispose();
  577. }
  578. }
  579. };
  580. /**
  581. * Provides a set of static methods for creating Disposables.
  582. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
  583. */
  584. var Disposable = Rx.Disposable = function (action) {
  585. this.isDisposed = false;
  586. this.action = action || noop;
  587. };
  588. /** Performs the task of cleaning up resources. */
  589. Disposable.prototype.dispose = function () {
  590. if (!this.isDisposed) {
  591. this.action();
  592. this.isDisposed = true;
  593. }
  594. };
  595. /**
  596. * Creates a disposable object that invokes the specified action when disposed.
  597. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
  598. * @return {Disposable} The disposable object that runs the given action upon disposal.
  599. */
  600. var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
  601. /**
  602. * Gets the disposable that does nothing when disposed.
  603. */
  604. var disposableEmpty = Disposable.empty = { dispose: noop };
  605. /**
  606. * Validates whether the given object is a disposable
  607. * @param {Object} Object to test whether it has a dispose method
  608. * @returns {Boolean} true if a disposable object, else false.
  609. */
  610. var isDisposable = Disposable.isDisposable = function (d) {
  611. return d && isFunction(d.dispose);
  612. };
  613. var checkDisposed = Disposable.checkDisposed = function (disposable) {
  614. if (disposable.isDisposed) { throw new ObjectDisposedError(); }
  615. };
  616. var disposableFixup = Disposable._fixup = function (result) {
  617. return isDisposable(result) ? result : disposableEmpty;
  618. };
  619. // Single assignment
  620. var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
  621. this.isDisposed = false;
  622. this.current = null;
  623. };
  624. SingleAssignmentDisposable.prototype.getDisposable = function () {
  625. return this.current;
  626. };
  627. SingleAssignmentDisposable.prototype.setDisposable = function (value) {
  628. if (this.current) { throw new Error('Disposable has already been assigned'); }
  629. var shouldDispose = this.isDisposed;
  630. !shouldDispose && (this.current = value);
  631. shouldDispose && value && value.dispose();
  632. };
  633. SingleAssignmentDisposable.prototype.dispose = function () {
  634. if (!this.isDisposed) {
  635. this.isDisposed = true;
  636. var old = this.current;
  637. this.current = null;
  638. old && old.dispose();
  639. }
  640. };
  641. // Multiple assignment disposable
  642. var SerialDisposable = Rx.SerialDisposable = function () {
  643. this.isDisposed = false;
  644. this.current = null;
  645. };
  646. SerialDisposable.prototype.getDisposable = function () {
  647. return this.current;
  648. };
  649. SerialDisposable.prototype.setDisposable = function (value) {
  650. var shouldDispose = this.isDisposed;
  651. if (!shouldDispose) {
  652. var old = this.current;
  653. this.current = value;
  654. }
  655. old && old.dispose();
  656. shouldDispose && value && value.dispose();
  657. };
  658. SerialDisposable.prototype.dispose = function () {
  659. if (!this.isDisposed) {
  660. this.isDisposed = true;
  661. var old = this.current;
  662. this.current = null;
  663. }
  664. old && old.dispose();
  665. };
  666. var BinaryDisposable = Rx.BinaryDisposable = function (first, second) {
  667. this._first = first;
  668. this._second = second;
  669. this.isDisposed = false;
  670. };
  671. BinaryDisposable.prototype.dispose = function () {
  672. if (!this.isDisposed) {
  673. this.isDisposed = true;
  674. var old1 = this._first;
  675. this._first = null;
  676. old1 && old1.dispose();
  677. var old2 = this._second;
  678. this._second = null;
  679. old2 && old2.dispose();
  680. }
  681. };
  682. var NAryDisposable = Rx.NAryDisposable = function (disposables) {
  683. this._disposables = disposables;
  684. this.isDisposed = false;
  685. };
  686. NAryDisposable.prototype.dispose = function () {
  687. if (!this.isDisposed) {
  688. this.isDisposed = true;
  689. for (var i = 0, len = this._disposables.length; i < len; i++) {
  690. this._disposables[i].dispose();
  691. }
  692. this._disposables.length = 0;
  693. }
  694. };
  695. /**
  696. * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
  697. */
  698. var RefCountDisposable = Rx.RefCountDisposable = (function () {
  699. function InnerDisposable(disposable) {
  700. this.disposable = disposable;
  701. this.disposable.count++;
  702. this.isInnerDisposed = false;
  703. }
  704. InnerDisposable.prototype.dispose = function () {
  705. if (!this.disposable.isDisposed && !this.isInnerDisposed) {
  706. this.isInnerDisposed = true;
  707. this.disposable.count--;
  708. if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
  709. this.disposable.isDisposed = true;
  710. this.disposable.underlyingDisposable.dispose();
  711. }
  712. }
  713. };
  714. /**
  715. * Initializes a new instance of the RefCountDisposable with the specified disposable.
  716. * @constructor
  717. * @param {Disposable} disposable Underlying disposable.
  718. */
  719. function RefCountDisposable(disposable) {
  720. this.underlyingDisposable = disposable;
  721. this.isDisposed = false;
  722. this.isPrimaryDisposed = false;
  723. this.count = 0;
  724. }
  725. /**
  726. * Disposes the underlying disposable only when all dependent disposables have been disposed
  727. */
  728. RefCountDisposable.prototype.dispose = function () {
  729. if (!this.isDisposed && !this.isPrimaryDisposed) {
  730. this.isPrimaryDisposed = true;
  731. if (this.count === 0) {
  732. this.isDisposed = true;
  733. this.underlyingDisposable.dispose();
  734. }
  735. }
  736. };
  737. /**
  738. * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
  739. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
  740. */
  741. RefCountDisposable.prototype.getDisposable = function () {
  742. return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
  743. };
  744. return RefCountDisposable;
  745. })();
  746. var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
  747. this.scheduler = scheduler;
  748. this.state = state;
  749. this.action = action;
  750. this.dueTime = dueTime;
  751. this.comparer = comparer || defaultSubComparer;
  752. this.disposable = new SingleAssignmentDisposable();
  753. };
  754. ScheduledItem.prototype.invoke = function () {
  755. this.disposable.setDisposable(this.invokeCore());
  756. };
  757. ScheduledItem.prototype.compareTo = function (other) {
  758. return this.comparer(this.dueTime, other.dueTime);
  759. };
  760. ScheduledItem.prototype.isCancelled = function () {
  761. return this.disposable.isDisposed;
  762. };
  763. ScheduledItem.prototype.invokeCore = function () {
  764. return disposableFixup(this.action(this.scheduler, this.state));
  765. };
  766. /** Provides a set of static properties to access commonly used schedulers. */
  767. var Scheduler = Rx.Scheduler = (function () {
  768. function Scheduler() { }
  769. /** Determines whether the given object is a scheduler */
  770. Scheduler.isScheduler = function (s) {
  771. return s instanceof Scheduler;
  772. };
  773. var schedulerProto = Scheduler.prototype;
  774. /**
  775. * Schedules an action to be executed.
  776. * @param state State passed to the action to be executed.
  777. * @param {Function} action Action to be executed.
  778. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  779. */
  780. schedulerProto.schedule = function (state, action) {
  781. throw new NotImplementedError();
  782. };
  783. /**
  784. * Schedules an action to be executed after dueTime.
  785. * @param state State passed to the action to be executed.
  786. * @param {Function} action Action to be executed.
  787. * @param {Number} dueTime Relative time after which to execute the action.
  788. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  789. */
  790. schedulerProto.scheduleFuture = function (state, dueTime, action) {
  791. var dt = dueTime;
  792. dt instanceof Date && (dt = dt - this.now());
  793. dt = Scheduler.normalize(dt);
  794. if (dt === 0) { return this.schedule(state, action); }
  795. return this._scheduleFuture(state, dt, action);
  796. };
  797. schedulerProto._scheduleFuture = function (state, dueTime, action) {
  798. throw new NotImplementedError();
  799. };
  800. /** Gets the current time according to the local machine's system clock. */
  801. Scheduler.now = defaultNow;
  802. /** Gets the current time according to the local machine's system clock. */
  803. Scheduler.prototype.now = defaultNow;
  804. /**
  805. * Normalizes the specified TimeSpan value to a positive value.
  806. * @param {Number} timeSpan The time span value to normalize.
  807. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
  808. */
  809. Scheduler.normalize = function (timeSpan) {
  810. timeSpan < 0 && (timeSpan = 0);
  811. return timeSpan;
  812. };
  813. return Scheduler;
  814. }());
  815. var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
  816. (function (schedulerProto) {
  817. function invokeRecImmediate(scheduler, pair) {
  818. var state = pair[0], action = pair[1], group = new CompositeDisposable();
  819. action(state, innerAction);
  820. return group;
  821. function innerAction(state2) {
  822. var isAdded = false, isDone = false;
  823. var d = scheduler.schedule(state2, scheduleWork);
  824. if (!isDone) {
  825. group.add(d);
  826. isAdded = true;
  827. }
  828. function scheduleWork(_, state3) {
  829. if (isAdded) {
  830. group.remove(d);
  831. } else {
  832. isDone = true;
  833. }
  834. action(state3, innerAction);
  835. return disposableEmpty;
  836. }
  837. }
  838. }
  839. function invokeRecDate(scheduler, pair) {
  840. var state = pair[0], action = pair[1], group = new CompositeDisposable();
  841. action(state, innerAction);
  842. return group;
  843. function innerAction(state2, dueTime1) {
  844. var isAdded = false, isDone = false;
  845. var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork);
  846. if (!isDone) {
  847. group.add(d);
  848. isAdded = true;
  849. }
  850. function scheduleWork(_, state3) {
  851. if (isAdded) {
  852. group.remove(d);
  853. } else {
  854. isDone = true;
  855. }
  856. action(state3, innerAction);
  857. return disposableEmpty;
  858. }
  859. }
  860. }
  861. /**
  862. * Schedules an action to be executed recursively.
  863. * @param {Mixed} state State passed to the action to be executed.
  864. * @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.
  865. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  866. */
  867. schedulerProto.scheduleRecursive = function (state, action) {
  868. return this.schedule([state, action], invokeRecImmediate);
  869. };
  870. /**
  871. * Schedules an action to be executed recursively after a specified relative or absolute due time.
  872. * @param {Mixed} state State passed to the action to be executed.
  873. * @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.
  874. * @param {Number | Date} dueTime Relative or absolute time after which to execute the action for the first time.
  875. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
  876. */
  877. schedulerProto.scheduleRecursiveFuture = function (state, dueTime, action) {
  878. return this.scheduleFuture([state, action], dueTime, invokeRecDate);
  879. };
  880. }(Scheduler.prototype));
  881. (function (schedulerProto) {
  882. /**
  883. * 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.
  884. * @param {Mixed} state Initial state passed to the action upon the first iteration.
  885. * @param {Number} period Period for running the work periodically.
  886. * @param {Function} action Action to be executed, potentially updating the state.
  887. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
  888. */
  889. schedulerProto.schedulePeriodic = function(state, period, action) {
  890. if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
  891. period = normalizeTime(period);
  892. var s = state, id = root.setInterval(function () { s = action(s); }, period);
  893. return disposableCreate(function () { root.clearInterval(id); });
  894. };
  895. }(Scheduler.prototype));
  896. /** Gets a scheduler that schedules work immediately on the current thread. */
  897. var ImmediateScheduler = (function (__super__) {
  898. inherits(ImmediateScheduler, __super__);
  899. function ImmediateScheduler() {
  900. __super__.call(this);
  901. }
  902. ImmediateScheduler.prototype.schedule = function (state, action) {
  903. return disposableFixup(action(this, state));
  904. };
  905. return ImmediateScheduler;
  906. }(Scheduler));
  907. var immediateScheduler = Scheduler.immediate = new ImmediateScheduler();
  908. /**
  909. * Gets a scheduler that schedules work as soon as possible on the current thread.
  910. */
  911. var CurrentThreadScheduler = (function (__super__) {
  912. var queue;
  913. function runTrampoline () {
  914. while (queue.length > 0) {
  915. var item = queue.dequeue();
  916. !item.isCancelled() && item.invoke();
  917. }
  918. }
  919. inherits(CurrentThreadScheduler, __super__);
  920. function CurrentThreadScheduler() {
  921. __super__.call(this);
  922. }
  923. CurrentThreadScheduler.prototype.schedule = function (state, action) {
  924. var si = new ScheduledItem(this, state, action, this.now());
  925. if (!queue) {
  926. queue = new PriorityQueue(4);
  927. queue.enqueue(si);
  928. var result = tryCatch(runTrampoline)();
  929. queue = null;
  930. if (result === errorObj) { thrower(result.e); }
  931. } else {
  932. queue.enqueue(si);
  933. }
  934. return si.disposable;
  935. };
  936. CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; };
  937. return CurrentThreadScheduler;
  938. }(Scheduler));
  939. var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler();
  940. var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
  941. function createTick(self) {
  942. return function tick(command, recurse) {
  943. recurse(0, self._period);
  944. var state = tryCatch(self._action)(self._state);
  945. if (state === errorObj) {
  946. self._cancel.dispose();
  947. thrower(state.e);
  948. }
  949. self._state = state;
  950. };
  951. }
  952. function SchedulePeriodicRecursive(scheduler, state, period, action) {
  953. this._scheduler = scheduler;
  954. this._state = state;
  955. this._period = period;
  956. this._action = action;
  957. }
  958. SchedulePeriodicRecursive.prototype.start = function () {
  959. var d = new SingleAssignmentDisposable();
  960. this._cancel = d;
  961. d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this)));
  962. return d;
  963. };
  964. return SchedulePeriodicRecursive;
  965. }());
  966. var scheduleMethod, clearMethod;
  967. var localTimer = (function () {
  968. var localSetTimeout, localClearTimeout = noop;
  969. if (!!root.setTimeout) {
  970. localSetTimeout = root.setTimeout;
  971. localClearTimeout = root.clearTimeout;
  972. } else if (!!root.WScript) {
  973. localSetTimeout = function (fn, time) {
  974. root.WScript.Sleep(time);
  975. fn();
  976. };
  977. } else {
  978. throw new NotSupportedError();
  979. }
  980. return {
  981. setTimeout: localSetTimeout,
  982. clearTimeout: localClearTimeout
  983. };
  984. }());
  985. var localSetTimeout = localTimer.setTimeout,
  986. localClearTimeout = localTimer.clearTimeout;
  987. (function () {
  988. var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
  989. clearMethod = function (handle) {
  990. delete tasksByHandle[handle];
  991. };
  992. function runTask(handle) {
  993. if (currentlyRunning) {
  994. localSetTimeout(function () { runTask(handle); }, 0);
  995. } else {
  996. var task = tasksByHandle[handle];
  997. if (task) {
  998. currentlyRunning = true;
  999. var result = tryCatch(task)();
  1000. clearMethod(handle);
  1001. currentlyRunning = false;
  1002. if (result === errorObj) { thrower(result.e); }
  1003. }
  1004. }
  1005. }
  1006. var reNative = new RegExp('^' +
  1007. String(toString)
  1008. .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  1009. .replace(/toString| for [^\]]+/g, '.*?') + '$'
  1010. );
  1011. var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
  1012. !reNative.test(setImmediate) && setImmediate;
  1013. function postMessageSupported () {
  1014. // Ensure not in a worker
  1015. if (!root.postMessage || root.importScripts) { return false; }
  1016. var isAsync = false, oldHandler = root.onmessage;
  1017. // Test for async
  1018. root.onmessage = function () { isAsync = true; };
  1019. root.postMessage('', '*');
  1020. root.onmessage = oldHandler;
  1021. return isAsync;
  1022. }
  1023. // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
  1024. if (isFunction(setImmediate)) {
  1025. scheduleMethod = function (action) {
  1026. var id = nextHandle++;
  1027. tasksByHandle[id] = action;
  1028. setImmediate(function () { runTask(id); });
  1029. return id;
  1030. };
  1031. } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
  1032. scheduleMethod = function (action) {
  1033. var id = nextHandle++;
  1034. tasksByHandle[id] = action;
  1035. process.nextTick(function () { runTask(id); });
  1036. return id;
  1037. };
  1038. } else if (postMessageSupported()) {
  1039. var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
  1040. var onGlobalPostMessage = function (event) {
  1041. // Only if we're a match to avoid any other global events
  1042. if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
  1043. runTask(event.data.substring(MSG_PREFIX.length));
  1044. }
  1045. };
  1046. root.addEventListener('message', onGlobalPostMessage, false);
  1047. scheduleMethod = function (action) {
  1048. var id = nextHandle++;
  1049. tasksByHandle[id] = action;
  1050. root.postMessage(MSG_PREFIX + id, '*');
  1051. return id;
  1052. };
  1053. } else if (!!root.MessageChannel) {
  1054. var channel = new root.MessageChannel();
  1055. channel.port1.onmessage = function (e) { runTask(e.data); };
  1056. scheduleMethod = function (action) {
  1057. var id = nextHandle++;
  1058. tasksByHandle[id] = action;
  1059. channel.port2.postMessage(id);
  1060. return id;
  1061. };
  1062. } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
  1063. scheduleMethod = function (action) {
  1064. var scriptElement = root.document.createElement('script');
  1065. var id = nextHandle++;
  1066. tasksByHandle[id] = action;
  1067. scriptElement.onreadystatechange = function () {
  1068. runTask(id);
  1069. scriptElement.onreadystatechange = null;
  1070. scriptElement.parentNode.removeChild(scriptElement);
  1071. scriptElement = null;
  1072. };
  1073. root.document.documentElement.appendChild(scriptElement);
  1074. return id;
  1075. };
  1076. } else {
  1077. scheduleMethod = function (action) {
  1078. var id = nextHandle++;
  1079. tasksByHandle[id] = action;
  1080. localSetTimeout(function () {
  1081. runTask(id);
  1082. }, 0);
  1083. return id;
  1084. };
  1085. }
  1086. }());
  1087. /**
  1088. * Gets a scheduler that schedules work via a timed callback based upon platform.
  1089. */
  1090. var DefaultScheduler = (function (__super__) {
  1091. inherits(DefaultScheduler, __super__);
  1092. function DefaultScheduler() {
  1093. __super__.call(this);
  1094. }
  1095. function scheduleAction(disposable, action, scheduler, state) {
  1096. return function schedule() {
  1097. disposable.setDisposable(Disposable._fixup(action(scheduler, state)));
  1098. };
  1099. }
  1100. function ClearDisposable(id) {
  1101. this._id = id;
  1102. this.isDisposed = false;
  1103. }
  1104. ClearDisposable.prototype.dispose = function () {
  1105. if (!this.isDisposed) {
  1106. this.isDisposed = true;
  1107. clearMethod(this._id);
  1108. }
  1109. };
  1110. function LocalClearDisposable(id) {
  1111. this._id = id;
  1112. this.isDisposed = false;
  1113. }
  1114. LocalClearDisposable.prototype.dispose = function () {
  1115. if (!this.isDisposed) {
  1116. this.isDisposed = true;
  1117. localClearTimeout(this._id);
  1118. }
  1119. };
  1120. DefaultScheduler.prototype.schedule = function (state, action) {
  1121. var disposable = new SingleAssignmentDisposable(),
  1122. id = scheduleMethod(scheduleAction(disposable, action, this, state));
  1123. return new BinaryDisposable(disposable, new ClearDisposable(id));
  1124. };
  1125. DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
  1126. if (dueTime === 0) { return this.schedule(state, action); }
  1127. var disposable = new SingleAssignmentDisposable(),
  1128. id = localSetTimeout(scheduleAction(disposable, action, this, state), dueTime);
  1129. return new BinaryDisposable(disposable, new LocalClearDisposable(id));
  1130. };
  1131. return DefaultScheduler;
  1132. }(Scheduler));
  1133. var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler();
  1134. function IndexedItem(id, value) {
  1135. this.id = id;
  1136. this.value = value;
  1137. }
  1138. IndexedItem.prototype.compareTo = function (other) {
  1139. var c = this.value.compareTo(other.value);
  1140. c === 0 && (c = this.id - other.id);
  1141. return c;
  1142. };
  1143. var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
  1144. this.items = new Array(capacity);
  1145. this.length = 0;
  1146. };
  1147. var priorityProto = PriorityQueue.prototype;
  1148. priorityProto.isHigherPriority = function (left, right) {
  1149. return this.items[left].compareTo(this.items[right]) < 0;
  1150. };
  1151. priorityProto.percolate = function (index) {
  1152. if (index >= this.length || index < 0) { return; }
  1153. var parent = index - 1 >> 1;
  1154. if (parent < 0 || parent === index) { return; }
  1155. if (this.isHigherPriority(index, parent)) {
  1156. var temp = this.items[index];
  1157. this.items[index] = this.items[parent];
  1158. this.items[parent] = temp;
  1159. this.percolate(parent);
  1160. }
  1161. };
  1162. priorityProto.heapify = function (index) {
  1163. +index || (index = 0);
  1164. if (index >= this.length || index < 0) { return; }
  1165. var left = 2 * index + 1,
  1166. right = 2 * index + 2,
  1167. first = index;
  1168. if (left < this.length && this.isHigherPriority(left, first)) {
  1169. first = left;
  1170. }
  1171. if (right < this.length && this.isHigherPriority(right, first)) {
  1172. first = right;
  1173. }
  1174. if (first !== index) {
  1175. var temp = this.items[index];
  1176. this.items[index] = this.items[first];
  1177. this.items[first] = temp;
  1178. this.heapify(first);
  1179. }
  1180. };
  1181. priorityProto.peek = function () { return this.items[0].value; };
  1182. priorityProto.removeAt = function (index) {
  1183. this.items[index] = this.items[--this.length];
  1184. this.items[this.length] = undefined;
  1185. this.heapify();
  1186. };
  1187. priorityProto.dequeue = function () {
  1188. var result = this.peek();
  1189. this.removeAt(0);
  1190. return result;
  1191. };
  1192. priorityProto.enqueue = function (item) {
  1193. var index = this.length++;
  1194. this.items[index] = new IndexedItem(PriorityQueue.count++, item);
  1195. this.percolate(index);
  1196. };
  1197. priorityProto.remove = function (item) {
  1198. for (var i = 0; i < this.length; i++) {
  1199. if (this.items[i].value === item) {
  1200. this.removeAt(i);
  1201. return true;
  1202. }
  1203. }
  1204. return false;
  1205. };
  1206. PriorityQueue.count = 0;
  1207. /**
  1208. * Represents a notification to an observer.
  1209. */
  1210. var Notification = Rx.Notification = (function () {
  1211. function Notification() {
  1212. }
  1213. Notification.prototype._accept = function (onNext, onError, onCompleted) {
  1214. throw new NotImplementedError();
  1215. };
  1216. Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) {
  1217. throw new NotImplementedError();
  1218. };
  1219. /**
  1220. * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
  1221. * @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on..
  1222. * @param {Function} onError Function to invoke for an OnError notification.
  1223. * @param {Function} onCompleted Function to invoke for an OnCompleted notification.
  1224. * @returns {Any} Result produced by the observation.
  1225. */
  1226. Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
  1227. return observerOrOnNext && typeof observerOrOnNext === 'object' ?
  1228. this._acceptObserver(observerOrOnNext) :
  1229. this._accept(observerOrOnNext, onError, onCompleted);
  1230. };
  1231. /**
  1232. * Returns an observable sequence with a single notification.
  1233. *
  1234. * @memberOf Notifications
  1235. * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
  1236. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
  1237. */
  1238. Notification.prototype.toObservable = function (scheduler) {
  1239. var self = this;
  1240. isScheduler(scheduler) || (scheduler = immediateScheduler);
  1241. return new AnonymousObservable(function (o) {
  1242. return scheduler.schedule(self, function (_, notification) {
  1243. notification._acceptObserver(o);
  1244. notification.kind === 'N' && o.onCompleted();
  1245. });
  1246. });
  1247. };
  1248. return Notification;
  1249. })();
  1250. var OnNextNotification = (function (__super__) {
  1251. inherits(OnNextNotification, __super__);
  1252. function OnNextNotification(value) {
  1253. this.value = value;
  1254. this.kind = 'N';
  1255. }
  1256. OnNextNotification.prototype._accept = function (onNext) {
  1257. return onNext(this.value);
  1258. };
  1259. OnNextNotification.prototype._acceptObserver = function (o) {
  1260. return o.onNext(this.value);
  1261. };
  1262. OnNextNotification.prototype.toString = function () {
  1263. return 'OnNext(' + this.value + ')';
  1264. };
  1265. return OnNextNotification;
  1266. }(Notification));
  1267. var OnErrorNotification = (function (__super__) {
  1268. inherits(OnErrorNotification, __super__);
  1269. function OnErrorNotification(error) {
  1270. this.error = error;
  1271. this.kind = 'E';
  1272. }
  1273. OnErrorNotification.prototype._accept = function (onNext, onError) {
  1274. return onError(this.error);
  1275. };
  1276. OnErrorNotification.prototype._acceptObserver = function (o) {
  1277. return o.onError(this.error);
  1278. };
  1279. OnErrorNotification.prototype.toString = function () {
  1280. return 'OnError(' + this.error + ')';
  1281. };
  1282. return OnErrorNotification;
  1283. }(Notification));
  1284. var OnCompletedNotification = (function (__super__) {
  1285. inherits(OnCompletedNotification, __super__);
  1286. function OnCompletedNotification() {
  1287. this.kind = 'C';
  1288. }
  1289. OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) {
  1290. return onCompleted();
  1291. };
  1292. OnCompletedNotification.prototype._acceptObserver = function (o) {
  1293. return o.onCompleted();
  1294. };
  1295. OnCompletedNotification.prototype.toString = function () {
  1296. return 'OnCompleted()';
  1297. };
  1298. return OnCompletedNotification;
  1299. }(Notification));
  1300. /**
  1301. * Creates an object that represents an OnNext notification to an observer.
  1302. * @param {Any} value The value contained in the notification.
  1303. * @returns {Notification} The OnNext notification containing the value.
  1304. */
  1305. var notificationCreateOnNext = Notification.createOnNext = function (value) {
  1306. return new OnNextNotification(value);
  1307. };
  1308. /**
  1309. * Creates an object that represents an OnError notification to an observer.
  1310. * @param {Any} error The exception contained in the notification.
  1311. * @returns {Notification} The OnError notification containing the exception.
  1312. */
  1313. var notificationCreateOnError = Notification.createOnError = function (error) {
  1314. return new OnErrorNotification(error);
  1315. };
  1316. /**
  1317. * Creates an object that represents an OnCompleted notification to an observer.
  1318. * @returns {Notification} The OnCompleted notification.
  1319. */
  1320. var notificationCreateOnCompleted = Notification.createOnCompleted = function () {
  1321. return new OnCompletedNotification();
  1322. };
  1323. /**
  1324. * Supports push-style iteration over an observable sequence.
  1325. */
  1326. var Observer = Rx.Observer = function () { };
  1327. /**
  1328. * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
  1329. * @param {Function} [onNext] Observer's OnNext action implementation.
  1330. * @param {Function} [onError] Observer's OnError action implementation.
  1331. * @param {Function} [onCompleted] Observer's OnCompleted action implementation.
  1332. * @returns {Observer} The observer object implemented using the given actions.
  1333. */
  1334. var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
  1335. onNext || (onNext = noop);
  1336. onError || (onError = defaultError);
  1337. onCompleted || (onCompleted = noop);
  1338. return new AnonymousObserver(onNext, onError, onCompleted);
  1339. };
  1340. /**
  1341. * Abstract base class for implementations of the Observer class.
  1342. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
  1343. */
  1344. var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
  1345. inherits(AbstractObserver, __super__);
  1346. /**
  1347. * Creates a new observer in a non-stopped state.
  1348. */
  1349. function AbstractObserver() {
  1350. this.isStopped = false;
  1351. }
  1352. // Must be implemented by other observers
  1353. AbstractObserver.prototype.next = notImplemented;
  1354. AbstractObserver.prototype.error = notImplemented;
  1355. AbstractObserver.prototype.completed = notImplemented;
  1356. /**
  1357. * Notifies the observer of a new element in the sequence.
  1358. * @param {Any} value Next element in the sequence.
  1359. */
  1360. AbstractObserver.prototype.onNext = function (value) {
  1361. !this.isStopped && this.next(value);
  1362. };
  1363. /**
  1364. * Notifies the observer that an exception has occurred.
  1365. * @param {Any} error The error that has occurred.
  1366. */
  1367. AbstractObserver.prototype.onError = function (error) {
  1368. if (!this.isStopped) {
  1369. this.isStopped = true;
  1370. this.error(error);
  1371. }
  1372. };
  1373. /**
  1374. * Notifies the observer of the end of the sequence.
  1375. */
  1376. AbstractObserver.prototype.onCompleted = function () {
  1377. if (!this.isStopped) {
  1378. this.isStopped = true;
  1379. this.completed();
  1380. }
  1381. };
  1382. /**
  1383. * Disposes the observer, causing it to transition to the stopped state.
  1384. */
  1385. AbstractObserver.prototype.dispose = function () { this.isStopped = true; };
  1386. AbstractObserver.prototype.fail = function (e) {
  1387. if (!this.isStopped) {
  1388. this.isStopped = true;
  1389. this.error(e);
  1390. return true;
  1391. }
  1392. return false;
  1393. };
  1394. return AbstractObserver;
  1395. }(Observer));
  1396. /**
  1397. * Class to create an Observer instance from delegate-based implementations of the on* methods.
  1398. */
  1399. var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
  1400. inherits(AnonymousObserver, __super__);
  1401. /**
  1402. * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
  1403. * @param {Any} onNext Observer's OnNext action implementation.
  1404. * @param {Any} onError Observer's OnError action implementation.
  1405. * @param {Any} onCompleted Observer's OnCompleted action implementation.
  1406. */
  1407. function AnonymousObserver(onNext, onError, onCompleted) {
  1408. __super__.call(this);
  1409. this._onNext = onNext;
  1410. this._onError = onError;
  1411. this._onCompleted = onCompleted;
  1412. }
  1413. /**
  1414. * Calls the onNext action.
  1415. * @param {Any} value Next element in the sequence.
  1416. */
  1417. AnonymousObserver.prototype.next = function (value) {
  1418. this._onNext(value);
  1419. };
  1420. /**
  1421. * Calls the onError action.
  1422. * @param {Any} error The error that has occurred.
  1423. */
  1424. AnonymousObserver.prototype.error = function (error) {
  1425. this._onError(error);
  1426. };
  1427. /**
  1428. * Calls the onCompleted action.
  1429. */
  1430. AnonymousObserver.prototype.completed = function () {
  1431. this._onCompleted();
  1432. };
  1433. return AnonymousObserver;
  1434. }(AbstractObserver));
  1435. var observableProto;
  1436. /**
  1437. * Represents a push-style collection.
  1438. */
  1439. var Observable = Rx.Observable = (function () {
  1440. function makeSubscribe(self, subscribe) {
  1441. return function (o) {
  1442. var oldOnError = o.onError;
  1443. o.onError = function (e) {
  1444. makeStackTraceLong(e, self);
  1445. oldOnError.call(o, e);
  1446. };
  1447. return subscribe.call(self, o);
  1448. };
  1449. }
  1450. function Observable() {
  1451. if (Rx.config.longStackSupport && hasStacks) {
  1452. var oldSubscribe = this._subscribe;
  1453. var e = tryCatch(thrower)(new Error()).e;
  1454. this.stack = e.stack.substring(e.stack.indexOf('\n') + 1);
  1455. this._subscribe = makeSubscribe(this, oldSubscribe);
  1456. }
  1457. }
  1458. observableProto = Observable.prototype;
  1459. /**
  1460. * Determines whether the given object is an Observable
  1461. * @param {Any} An object to determine whether it is an Observable
  1462. * @returns {Boolean} true if an Observable, else false.
  1463. */
  1464. Observable.isObservable = function (o) {
  1465. return o && isFunction(o.subscribe);
  1466. };
  1467. /**
  1468. * Subscribes an o to the observable sequence.
  1469. * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
  1470. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
  1471. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
  1472. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
  1473. */
  1474. observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
  1475. return this._subscribe(typeof oOrOnNext === 'object' ?
  1476. oOrOnNext :
  1477. observerCreate(oOrOnNext, onError, onCompleted));
  1478. };
  1479. /**
  1480. * Subscribes to the next value in the sequence with an optional "this" argument.
  1481. * @param {Function} onNext The function to invoke on each element in the observable sequence.
  1482. * @param {Any} [thisArg] Object to use as this when executing callback.
  1483. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
  1484. */
  1485. observableProto.subscribeOnNext = function (onNext, thisArg) {
  1486. return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
  1487. };
  1488. /**
  1489. * Subscribes to an exceptional condition in the sequence with an optional "this" argument.
  1490. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
  1491. * @param {Any} [thisArg] Object to use as this when executing callback.
  1492. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
  1493. */
  1494. observableProto.subscribeOnError = function (onError, thisArg) {
  1495. return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
  1496. };
  1497. /**
  1498. * Subscribes to the next value in the sequence with an optional "this" argument.
  1499. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
  1500. * @param {Any} [thisArg] Object to use as this when executing callback.
  1501. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
  1502. */
  1503. observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
  1504. return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
  1505. };
  1506. return Observable;
  1507. })();
  1508. var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
  1509. inherits(ScheduledObserver, __super__);
  1510. function ScheduledObserver(scheduler, observer) {
  1511. __super__.call(this);
  1512. this.scheduler = scheduler;
  1513. this.observer = observer;
  1514. this.isAcquired = false;
  1515. this.hasFaulted = false;
  1516. this.queue = [];
  1517. this.disposable = new SerialDisposable();
  1518. }
  1519. function enqueueNext(observer, x) { return function () { observer.onNext(x); }; }
  1520. function enqueueError(observer, e) { return function () { observer.onError(e); }; }
  1521. function enqueueCompleted(observer) { return function () { observer.onCompleted(); }; }
  1522. ScheduledObserver.prototype.next = function (x) {
  1523. this.queue.push(enqueueNext(this.observer, x));
  1524. };
  1525. ScheduledObserver.prototype.error = function (e) {
  1526. this.queue.push(enqueueError(this.observer, e));
  1527. };
  1528. ScheduledObserver.prototype.completed = function () {
  1529. this.queue.push(enqueueCompleted(this.observer));
  1530. };
  1531. function scheduleMethod(state, recurse) {
  1532. var work;
  1533. if (state.queue.length > 0) {
  1534. work = state.queue.shift();
  1535. } else {
  1536. state.isAcquired = false;
  1537. return;
  1538. }
  1539. var res = tryCatch(work)();
  1540. if (res === errorObj) {
  1541. state.queue = [];
  1542. state.hasFaulted = true;
  1543. return thrower(res.e);
  1544. }
  1545. recurse(state);
  1546. }
  1547. ScheduledObserver.prototype.ensureActive = function () {
  1548. var isOwner = false;
  1549. if (!this.hasFaulted && this.queue.length > 0) {
  1550. isOwner = !this.isAcquired;
  1551. this.isAcquired = true;
  1552. }
  1553. isOwner &&
  1554. this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, scheduleMethod));
  1555. };
  1556. ScheduledObserver.prototype.dispose = function () {
  1557. __super__.prototype.dispose.call(this);
  1558. this.disposable.dispose();
  1559. };
  1560. return ScheduledObserver;
  1561. }(AbstractObserver));
  1562. var ObservableBase = Rx.ObservableBase = (function (__super__) {
  1563. inherits(ObservableBase, __super__);
  1564. function fixSubscriber(subscriber) {
  1565. return subscriber && isFunction(subscriber.dispose) ? subscriber :
  1566. isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
  1567. }
  1568. function setDisposable(s, state) {
  1569. var ado = state[0], self = state[1];
  1570. var sub = tryCatch(self.subscribeCore).call(self, ado);
  1571. if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
  1572. ado.setDisposable(fixSubscriber(sub));
  1573. }
  1574. function ObservableBase() {
  1575. __super__.call(this);
  1576. }
  1577. ObservableBase.prototype._subscribe = function (o) {
  1578. var ado = new AutoDetachObserver(o), state = [ado, this];
  1579. if (currentThreadScheduler.scheduleRequired()) {
  1580. currentThreadScheduler.schedule(state, setDisposable);
  1581. } else {
  1582. setDisposable(null, state);
  1583. }
  1584. return ado;
  1585. };
  1586. ObservableBase.prototype.subscribeCore = notImplemented;
  1587. return ObservableBase;
  1588. }(Observable));
  1589. var FlatMapObservable = Rx.FlatMapObservable = (function(__super__) {
  1590. inherits(FlatMapObservable, __super__);
  1591. function FlatMapObservable(source, selector, resultSelector, thisArg) {
  1592. this.resultSelector = isFunction(resultSelector) ? resultSelector : null;
  1593. this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3);
  1594. this.source = source;
  1595. __super__.call(this);
  1596. }
  1597. FlatMapObservable.prototype.subscribeCore = function(o) {
  1598. return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this));
  1599. };
  1600. inherits(InnerObserver, AbstractObserver);
  1601. function InnerObserver(observer, selector, resultSelector, source) {
  1602. this.i = 0;
  1603. this.selector = selector;
  1604. this.resultSelector = resultSelector;
  1605. this.source = source;
  1606. this.o = observer;
  1607. AbstractObserver.call(this);
  1608. }
  1609. InnerObserver.prototype._wrapResult = function(result, x, i) {
  1610. return this.resultSelector ?
  1611. result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) :
  1612. result;
  1613. };
  1614. InnerObserver.prototype.next = function(x) {
  1615. var i = this.i++;
  1616. var result = tryCatch(this.selector)(x, i, this.source);
  1617. if (result === errorObj) { return this.o.onError(result.e); }
  1618. isPromise(result) && (result = observableFromPromise(result));
  1619. (isArrayLike(result) || isIterable(result)) && (result = Observable.from(result));
  1620. this.o.onNext(this._wrapResult(result, x, i));
  1621. };
  1622. InnerObserver.prototype.error = function(e) { this.o.onError(e); };
  1623. InnerObserver.prototype.completed = function() { this.o.onCompleted(); };
  1624. return FlatMapObservable;
  1625. }(ObservableBase));
  1626. var Enumerable = Rx.internals.Enumerable = function () { };
  1627. function IsDisposedDisposable(state) {
  1628. this._s = state;
  1629. this.isDisposed = false;
  1630. }
  1631. IsDisposedDisposable.prototype.dispose = function () {
  1632. if (!this.isDisposed) {
  1633. this.isDisposed = true;
  1634. this._s.isDisposed = true;
  1635. }
  1636. };
  1637. var ConcatEnumerableObservable = (function(__super__) {
  1638. inherits(ConcatEnumerableObservable, __super__);
  1639. function ConcatEnumerableObservable(sources) {
  1640. this.sources = sources;
  1641. __super__.call(this);
  1642. }
  1643. function scheduleMethod(state, recurse) {
  1644. if (state.isDisposed) { return; }
  1645. var currentItem = tryCatch(state.e.next).call(state.e);
  1646. if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
  1647. if (currentItem.done) { return state.o.onCompleted(); }
  1648. // Check if promise
  1649. var currentValue = currentItem.value;
  1650. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  1651. var d = new SingleAssignmentDisposable();
  1652. state.subscription.setDisposable(d);
  1653. d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
  1654. }
  1655. ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
  1656. var subscription = new SerialDisposable();
  1657. var state = {
  1658. isDisposed: false,
  1659. o: o,
  1660. subscription: subscription,
  1661. e: this.sources[$iterator$]()
  1662. };
  1663. var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
  1664. return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
  1665. };
  1666. function InnerObserver(state, recurse) {
  1667. this._state = state;
  1668. this._recurse = recurse;
  1669. AbstractObserver.call(this);
  1670. }
  1671. inherits(InnerObserver, AbstractObserver);
  1672. InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  1673. InnerObserver.prototype.error = function (e) { this._state.o.onError(e); };
  1674. InnerObserver.prototype.completed = function () { this._recurse(this._state); };
  1675. return ConcatEnumerableObservable;
  1676. }(ObservableBase));
  1677. Enumerable.prototype.concat = function () {
  1678. return new ConcatEnumerableObservable(this);
  1679. };
  1680. var CatchErrorObservable = (function(__super__) {
  1681. function CatchErrorObservable(sources) {
  1682. this.sources = sources;
  1683. __super__.call(this);
  1684. }
  1685. inherits(CatchErrorObservable, __super__);
  1686. function scheduleMethod(state, recurse) {
  1687. if (state.isDisposed) { return; }
  1688. var currentItem = tryCatch(state.e.next).call(state.e);
  1689. if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
  1690. if (currentItem.done) { return state.lastError !== null ? state.o.onError(state.lastError) : state.o.onCompleted(); }
  1691. var currentValue = currentItem.value;
  1692. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  1693. var d = new SingleAssignmentDisposable();
  1694. state.subscription.setDisposable(d);
  1695. d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
  1696. }
  1697. CatchErrorObservable.prototype.subscribeCore = function (o) {
  1698. var subscription = new SerialDisposable();
  1699. var state = {
  1700. isDisposed: false,
  1701. e: this.sources[$iterator$](),
  1702. subscription: subscription,
  1703. lastError: null,
  1704. o: o
  1705. };
  1706. var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
  1707. return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
  1708. };
  1709. function InnerObserver(state, recurse) {
  1710. this._state = state;
  1711. this._recurse = recurse;
  1712. AbstractObserver.call(this);
  1713. }
  1714. inherits(InnerObserver, AbstractObserver);
  1715. InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  1716. InnerObserver.prototype.error = function (e) { this._state.lastError = e; this._recurse(this._state); };
  1717. InnerObserver.prototype.completed = function () { this._state.o.onCompleted(); };
  1718. return CatchErrorObservable;
  1719. }(ObservableBase));
  1720. Enumerable.prototype.catchError = function () {
  1721. return new CatchErrorObservable(this);
  1722. };
  1723. var RepeatEnumerable = (function (__super__) {
  1724. inherits(RepeatEnumerable, __super__);
  1725. function RepeatEnumerable(v, c) {
  1726. this.v = v;
  1727. this.c = c == null ? -1 : c;
  1728. }
  1729. RepeatEnumerable.prototype[$iterator$] = function () {
  1730. return new RepeatEnumerator(this);
  1731. };
  1732. function RepeatEnumerator(p) {
  1733. this.v = p.v;
  1734. this.l = p.c;
  1735. }
  1736. RepeatEnumerator.prototype.next = function () {
  1737. if (this.l === 0) { return doneEnumerator; }
  1738. if (this.l > 0) { this.l--; }
  1739. return { done: false, value: this.v };
  1740. };
  1741. return RepeatEnumerable;
  1742. }(Enumerable));
  1743. var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
  1744. return new RepeatEnumerable(value, repeatCount);
  1745. };
  1746. var OfEnumerable = (function(__super__) {
  1747. inherits(OfEnumerable, __super__);
  1748. function OfEnumerable(s, fn, thisArg) {
  1749. this.s = s;
  1750. this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
  1751. }
  1752. OfEnumerable.prototype[$iterator$] = function () {
  1753. return new OfEnumerator(this);
  1754. };
  1755. function OfEnumerator(p) {
  1756. this.i = -1;
  1757. this.s = p.s;
  1758. this.l = this.s.length;
  1759. this.fn = p.fn;
  1760. }
  1761. OfEnumerator.prototype.next = function () {
  1762. return ++this.i < this.l ?
  1763. { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
  1764. doneEnumerator;
  1765. };
  1766. return OfEnumerable;
  1767. }(Enumerable));
  1768. var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
  1769. return new OfEnumerable(source, selector, thisArg);
  1770. };
  1771. var ToArrayObservable = (function(__super__) {
  1772. inherits(ToArrayObservable, __super__);
  1773. function ToArrayObservable(source) {
  1774. this.source = source;
  1775. __super__.call(this);
  1776. }
  1777. ToArrayObservable.prototype.subscribeCore = function(o) {
  1778. return this.source.subscribe(new InnerObserver(o));
  1779. };
  1780. inherits(InnerObserver, AbstractObserver);
  1781. function InnerObserver(o) {
  1782. this.o = o;
  1783. this.a = [];
  1784. AbstractObserver.call(this);
  1785. }
  1786. InnerObserver.prototype.next = function (x) { this.a.push(x); };
  1787. InnerObserver.prototype.error = function (e) { this.o.onError(e); };
  1788. InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); };
  1789. return ToArrayObservable;
  1790. }(ObservableBase));
  1791. /**
  1792. * Creates an array from an observable sequence.
  1793. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
  1794. */
  1795. observableProto.toArray = function () {
  1796. return new ToArrayObservable(this);
  1797. };
  1798. /**
  1799. * Creates an observable sequence from a specified subscribe method implementation.
  1800. * @example
  1801. * var res = Rx.Observable.create(function (observer) { return function () { } );
  1802. * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
  1803. * var res = Rx.Observable.create(function (observer) { } );
  1804. * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
  1805. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
  1806. */
  1807. Observable.create = function (subscribe, parent) {
  1808. return new AnonymousObservable(subscribe, parent);
  1809. };
  1810. var Defer = (function(__super__) {
  1811. inherits(Defer, __super__);
  1812. function Defer(factory) {
  1813. this._f = factory;
  1814. __super__.call(this);
  1815. }
  1816. Defer.prototype.subscribeCore = function (o) {
  1817. var result = tryCatch(this._f)();
  1818. if (result === errorObj) { return observableThrow(result.e).subscribe(o);}
  1819. isPromise(result) && (result = observableFromPromise(result));
  1820. return result.subscribe(o);
  1821. };
  1822. return Defer;
  1823. }(ObservableBase));
  1824. /**
  1825. * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
  1826. *
  1827. * @example
  1828. * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
  1829. * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
  1830. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
  1831. */
  1832. var observableDefer = Observable.defer = function (observableFactory) {
  1833. return new Defer(observableFactory);
  1834. };
  1835. var EmptyObservable = (function(__super__) {
  1836. inherits(EmptyObservable, __super__);
  1837. function EmptyObservable(scheduler) {
  1838. this.scheduler = scheduler;
  1839. __super__.call(this);
  1840. }
  1841. EmptyObservable.prototype.subscribeCore = function (observer) {
  1842. var sink = new EmptySink(observer, this.scheduler);
  1843. return sink.run();
  1844. };
  1845. function EmptySink(observer, scheduler) {
  1846. this.observer = observer;
  1847. this.scheduler = scheduler;
  1848. }
  1849. function scheduleItem(s, state) {
  1850. state.onCompleted();
  1851. return disposableEmpty;
  1852. }
  1853. EmptySink.prototype.run = function () {
  1854. var state = this.observer;
  1855. return this.scheduler === immediateScheduler ?
  1856. scheduleItem(null, state) :
  1857. this.scheduler.schedule(state, scheduleItem);
  1858. };
  1859. return EmptyObservable;
  1860. }(ObservableBase));
  1861. var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler);
  1862. /**
  1863. * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
  1864. *
  1865. * @example
  1866. * var res = Rx.Observable.empty();
  1867. * var res = Rx.Observable.empty(Rx.Scheduler.timeout);
  1868. * @param {Scheduler} [scheduler] Scheduler to send the termination call on.
  1869. * @returns {Observable} An observable sequence with no elements.
  1870. */
  1871. var observableEmpty = Observable.empty = function (scheduler) {
  1872. isScheduler(scheduler) || (scheduler = immediateScheduler);
  1873. return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler);
  1874. };
  1875. var FromObservable = (function(__super__) {
  1876. inherits(FromObservable, __super__);
  1877. function FromObservable(iterable, fn, scheduler) {
  1878. this._iterable = iterable;
  1879. this._fn = fn;
  1880. this._scheduler = scheduler;
  1881. __super__.call(this);
  1882. }
  1883. function createScheduleMethod(o, it, fn) {
  1884. return function loopRecursive(i, recurse) {
  1885. var next = tryCatch(it.next).call(it);
  1886. if (next === errorObj) { return o.onError(next.e); }
  1887. if (next.done) { return o.onCompleted(); }
  1888. var result = next.value;
  1889. if (isFunction(fn)) {
  1890. result = tryCatch(fn)(result, i);
  1891. if (result === errorObj) { return o.onError(result.e); }
  1892. }
  1893. o.onNext(result);
  1894. recurse(i + 1);
  1895. };
  1896. }
  1897. FromObservable.prototype.subscribeCore = function (o) {
  1898. var list = Object(this._iterable),
  1899. it = getIterable(list);
  1900. return this._scheduler.scheduleRecursive(0, createScheduleMethod(o, it, this._fn));
  1901. };
  1902. return FromObservable;
  1903. }(ObservableBase));
  1904. var maxSafeInteger = Math.pow(2, 53) - 1;
  1905. function StringIterable(s) {
  1906. this._s = s;
  1907. }
  1908. StringIterable.prototype[$iterator$] = function () {
  1909. return new StringIterator(this._s);
  1910. };
  1911. function StringIterator(s) {
  1912. this._s = s;
  1913. this._l = s.length;
  1914. this._i = 0;
  1915. }
  1916. StringIterator.prototype[$iterator$] = function () {
  1917. return this;
  1918. };
  1919. StringIterator.prototype.next = function () {
  1920. return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
  1921. };
  1922. function ArrayIterable(a) {
  1923. this._a = a;
  1924. }
  1925. ArrayIterable.prototype[$iterator$] = function () {
  1926. return new ArrayIterator(this._a);
  1927. };
  1928. function ArrayIterator(a) {
  1929. this._a = a;
  1930. this._l = toLength(a);
  1931. this._i = 0;
  1932. }
  1933. ArrayIterator.prototype[$iterator$] = function () {
  1934. return this;
  1935. };
  1936. ArrayIterator.prototype.next = function () {
  1937. return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
  1938. };
  1939. function numberIsFinite(value) {
  1940. return typeof value === 'number' && root.isFinite(value);
  1941. }
  1942. function isNan(n) {
  1943. return n !== n;
  1944. }
  1945. function getIterable(o) {
  1946. var i = o[$iterator$], it;
  1947. if (!i && typeof o === 'string') {
  1948. it = new StringIterable(o);
  1949. return it[$iterator$]();
  1950. }
  1951. if (!i && o.length !== undefined) {
  1952. it = new ArrayIterable(o);
  1953. return it[$iterator$]();
  1954. }
  1955. if (!i) { throw new TypeError('Object is not iterable'); }
  1956. return o[$iterator$]();
  1957. }
  1958. function sign(value) {
  1959. var number = +value;
  1960. if (number === 0) { return number; }
  1961. if (isNaN(number)) { return number; }
  1962. return number < 0 ? -1 : 1;
  1963. }
  1964. function toLength(o) {
  1965. var len = +o.length;
  1966. if (isNaN(len)) { return 0; }
  1967. if (len === 0 || !numberIsFinite(len)) { return len; }
  1968. len = sign(len) * Math.floor(Math.abs(len));
  1969. if (len <= 0) { return 0; }
  1970. if (len > maxSafeInteger) { return maxSafeInteger; }
  1971. return len;
  1972. }
  1973. /**
  1974. * This method creates a new Observable sequence from an array-like or iterable object.
  1975. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
  1976. * @param {Function} [mapFn] Map function to call on every element of the array.
  1977. * @param {Any} [thisArg] The context to use calling the mapFn if provided.
  1978. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
  1979. */
  1980. var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
  1981. if (iterable == null) {
  1982. throw new Error('iterable cannot be null.')
  1983. }
  1984. if (mapFn && !isFunction(mapFn)) {
  1985. throw new Error('mapFn when provided must be a function');
  1986. }
  1987. if (mapFn) {
  1988. var mapper = bindCallback(mapFn, thisArg, 2);
  1989. }
  1990. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  1991. return new FromObservable(iterable, mapper, scheduler);
  1992. }
  1993. var FromArrayObservable = (function(__super__) {
  1994. inherits(FromArrayObservable, __super__);
  1995. function FromArrayObservable(args, scheduler) {
  1996. this._args = args;
  1997. this._scheduler = scheduler;
  1998. __super__.call(this);
  1999. }
  2000. function scheduleMethod(o, args) {
  2001. var len = args.length;
  2002. return function loopRecursive (i, recurse) {
  2003. if (i < len) {
  2004. o.onNext(args[i]);
  2005. recurse(i + 1);
  2006. } else {
  2007. o.onCompleted();
  2008. }
  2009. };
  2010. }
  2011. FromArrayObservable.prototype.subscribeCore = function (o) {
  2012. return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._args));
  2013. };
  2014. return FromArrayObservable;
  2015. }(ObservableBase));
  2016. /**
  2017. * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
  2018. * @deprecated use Observable.from or Observable.of
  2019. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
  2020. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
  2021. */
  2022. var observableFromArray = Observable.fromArray = function (array, scheduler) {
  2023. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2024. return new FromArrayObservable(array, scheduler)
  2025. };
  2026. var NeverObservable = (function(__super__) {
  2027. inherits(NeverObservable, __super__);
  2028. function NeverObservable() {
  2029. __super__.call(this);
  2030. }
  2031. NeverObservable.prototype.subscribeCore = function (observer) {
  2032. return disposableEmpty;
  2033. };
  2034. return NeverObservable;
  2035. }(ObservableBase));
  2036. var NEVER_OBSERVABLE = new NeverObservable();
  2037. /**
  2038. * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
  2039. * @returns {Observable} An observable sequence whose observers will never get called.
  2040. */
  2041. var observableNever = Observable.never = function () {
  2042. return NEVER_OBSERVABLE;
  2043. };
  2044. function observableOf (scheduler, array) {
  2045. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2046. return new FromArrayObservable(array, scheduler);
  2047. }
  2048. /**
  2049. * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
  2050. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
  2051. */
  2052. Observable.of = function () {
  2053. var len = arguments.length, args = new Array(len);
  2054. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2055. return new FromArrayObservable(args, currentThreadScheduler);
  2056. };
  2057. /**
  2058. * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
  2059. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
  2060. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
  2061. */
  2062. Observable.ofWithScheduler = function (scheduler) {
  2063. var len = arguments.length, args = new Array(len - 1);
  2064. for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
  2065. return new FromArrayObservable(args, scheduler);
  2066. };
  2067. var PairsObservable = (function(__super__) {
  2068. inherits(PairsObservable, __super__);
  2069. function PairsObservable(o, scheduler) {
  2070. this._o = o;
  2071. this._keys = Object.keys(o);
  2072. this._scheduler = scheduler;
  2073. __super__.call(this);
  2074. }
  2075. function scheduleMethod(o, obj, keys) {
  2076. return function loopRecursive(i, recurse) {
  2077. if (i < keys.length) {
  2078. var key = keys[i];
  2079. o.onNext([key, obj[key]]);
  2080. recurse(i + 1);
  2081. } else {
  2082. o.onCompleted();
  2083. }
  2084. };
  2085. }
  2086. PairsObservable.prototype.subscribeCore = function (o) {
  2087. return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._o, this._keys));
  2088. };
  2089. return PairsObservable;
  2090. }(ObservableBase));
  2091. /**
  2092. * Convert an object into an observable sequence of [key, value] pairs.
  2093. * @param {Object} obj The object to inspect.
  2094. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
  2095. * @returns {Observable} An observable sequence of [key, value] pairs from the object.
  2096. */
  2097. Observable.pairs = function (obj, scheduler) {
  2098. scheduler || (scheduler = currentThreadScheduler);
  2099. return new PairsObservable(obj, scheduler);
  2100. };
  2101. var RangeObservable = (function(__super__) {
  2102. inherits(RangeObservable, __super__);
  2103. function RangeObservable(start, count, scheduler) {
  2104. this.start = start;
  2105. this.rangeCount = count;
  2106. this.scheduler = scheduler;
  2107. __super__.call(this);
  2108. }
  2109. function loopRecursive(start, count, o) {
  2110. return function loop (i, recurse) {
  2111. if (i < count) {
  2112. o.onNext(start + i);
  2113. recurse(i + 1);
  2114. } else {
  2115. o.onCompleted();
  2116. }
  2117. };
  2118. }
  2119. RangeObservable.prototype.subscribeCore = function (o) {
  2120. return this.scheduler.scheduleRecursive(
  2121. 0,
  2122. loopRecursive(this.start, this.rangeCount, o)
  2123. );
  2124. };
  2125. return RangeObservable;
  2126. }(ObservableBase));
  2127. /**
  2128. * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
  2129. * @param {Number} start The value of the first integer in the sequence.
  2130. * @param {Number} count The number of sequential integers to generate.
  2131. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
  2132. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
  2133. */
  2134. Observable.range = function (start, count, scheduler) {
  2135. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2136. return new RangeObservable(start, count, scheduler);
  2137. };
  2138. var RepeatObservable = (function(__super__) {
  2139. inherits(RepeatObservable, __super__);
  2140. function RepeatObservable(value, repeatCount, scheduler) {
  2141. this.value = value;
  2142. this.repeatCount = repeatCount == null ? -1 : repeatCount;
  2143. this.scheduler = scheduler;
  2144. __super__.call(this);
  2145. }
  2146. RepeatObservable.prototype.subscribeCore = function (observer) {
  2147. var sink = new RepeatSink(observer, this);
  2148. return sink.run();
  2149. };
  2150. return RepeatObservable;
  2151. }(ObservableBase));
  2152. function RepeatSink(observer, parent) {
  2153. this.observer = observer;
  2154. this.parent = parent;
  2155. }
  2156. RepeatSink.prototype.run = function () {
  2157. var observer = this.observer, value = this.parent.value;
  2158. function loopRecursive(i, recurse) {
  2159. if (i === -1 || i > 0) {
  2160. observer.onNext(value);
  2161. i > 0 && i--;
  2162. }
  2163. if (i === 0) { return observer.onCompleted(); }
  2164. recurse(i);
  2165. }
  2166. return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive);
  2167. };
  2168. /**
  2169. * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
  2170. * @param {Mixed} value Element to repeat.
  2171. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
  2172. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
  2173. * @returns {Observable} An observable sequence that repeats the given element the specified number of times.
  2174. */
  2175. Observable.repeat = function (value, repeatCount, scheduler) {
  2176. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  2177. return new RepeatObservable(value, repeatCount, scheduler);
  2178. };
  2179. var JustObservable = (function(__super__) {
  2180. inherits(JustObservable, __super__);
  2181. function JustObservable(value, scheduler) {
  2182. this._value = value;
  2183. this._scheduler = scheduler;
  2184. __super__.call(this);
  2185. }
  2186. JustObservable.prototype.subscribeCore = function (o) {
  2187. var state = [this._value, o];
  2188. return this._scheduler === immediateScheduler ?
  2189. scheduleItem(null, state) :
  2190. this._scheduler.schedule(state, scheduleItem);
  2191. };
  2192. function scheduleItem(s, state) {
  2193. var value = state[0], observer = state[1];
  2194. observer.onNext(value);
  2195. observer.onCompleted();
  2196. return disposableEmpty;
  2197. }
  2198. return JustObservable;
  2199. }(ObservableBase));
  2200. /**
  2201. * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
  2202. * There is an alias called 'just' or browsers <IE9.
  2203. * @param {Mixed} value Single element in the resulting observable sequence.
  2204. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
  2205. * @returns {Observable} An observable sequence containing the single specified element.
  2206. */
  2207. var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
  2208. isScheduler(scheduler) || (scheduler = immediateScheduler);
  2209. return new JustObservable(value, scheduler);
  2210. };
  2211. var ThrowObservable = (function(__super__) {
  2212. inherits(ThrowObservable, __super__);
  2213. function ThrowObservable(error, scheduler) {
  2214. this._error = error;
  2215. this._scheduler = scheduler;
  2216. __super__.call(this);
  2217. }
  2218. ThrowObservable.prototype.subscribeCore = function (o) {
  2219. var state = [this._error, o];
  2220. return this._scheduler === immediateScheduler ?
  2221. scheduleItem(null, state) :
  2222. this._scheduler.schedule(state, scheduleItem);
  2223. };
  2224. function scheduleItem(s, state) {
  2225. var e = state[0], o = state[1];
  2226. o.onError(e);
  2227. return disposableEmpty;
  2228. }
  2229. return ThrowObservable;
  2230. }(ObservableBase));
  2231. /**
  2232. * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
  2233. * There is an alias to this method called 'throwError' for browsers <IE9.
  2234. * @param {Mixed} error An object used for the sequence's termination.
  2235. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
  2236. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
  2237. */
  2238. var observableThrow = Observable['throw'] = function (error, scheduler) {
  2239. isScheduler(scheduler) || (scheduler = immediateScheduler);
  2240. return new ThrowObservable(error, scheduler);
  2241. };
  2242. var CatchObservable = (function (__super__) {
  2243. inherits(CatchObservable, __super__);
  2244. function CatchObservable(source, fn) {
  2245. this.source = source;
  2246. this._fn = fn;
  2247. __super__.call(this);
  2248. }
  2249. CatchObservable.prototype.subscribeCore = function (o) {
  2250. var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
  2251. subscription.setDisposable(d1);
  2252. d1.setDisposable(this.source.subscribe(new CatchObserver(o, subscription, this._fn)));
  2253. return subscription;
  2254. };
  2255. return CatchObservable;
  2256. }(ObservableBase));
  2257. var CatchObserver = (function(__super__) {
  2258. inherits(CatchObserver, __super__);
  2259. function CatchObserver(o, s, fn) {
  2260. this._o = o;
  2261. this._s = s;
  2262. this._fn = fn;
  2263. __super__.call(this);
  2264. }
  2265. CatchObserver.prototype.next = function (x) { this._o.onNext(x); };
  2266. CatchObserver.prototype.completed = function () { return this._o.onCompleted(); };
  2267. CatchObserver.prototype.error = function (e) {
  2268. var result = tryCatch(this._fn)(e);
  2269. if (result === errorObj) { return this._o.onError(result.e); }
  2270. isPromise(result) && (result = observableFromPromise(result));
  2271. var d = new SingleAssignmentDisposable();
  2272. this._s.setDisposable(d);
  2273. d.setDisposable(result.subscribe(this._o));
  2274. };
  2275. return CatchObserver;
  2276. }(AbstractObserver));
  2277. /**
  2278. * Continues an observable sequence that is terminated by an exception with the next observable sequence.
  2279. * @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.
  2280. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
  2281. */
  2282. observableProto['catch'] = function (handlerOrSecond) {
  2283. return isFunction(handlerOrSecond) ? new CatchObservable(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]);
  2284. };
  2285. /**
  2286. * Continues an observable sequence that is terminated by an exception with the next observable sequence.
  2287. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
  2288. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
  2289. */
  2290. var observableCatch = Observable['catch'] = function () {
  2291. var items;
  2292. if (Array.isArray(arguments[0])) {
  2293. items = arguments[0];
  2294. } else {
  2295. var len = arguments.length;
  2296. items = new Array(len);
  2297. for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
  2298. }
  2299. return enumerableOf(items).catchError();
  2300. };
  2301. /**
  2302. * 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.
  2303. * This can be in the form of an argument list of observables or an array.
  2304. *
  2305. * @example
  2306. * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
  2307. * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
  2308. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  2309. */
  2310. observableProto.combineLatest = function () {
  2311. var len = arguments.length, args = new Array(len);
  2312. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2313. if (Array.isArray(args[0])) {
  2314. args[0].unshift(this);
  2315. } else {
  2316. args.unshift(this);
  2317. }
  2318. return combineLatest.apply(this, args);
  2319. };
  2320. function falseFactory() { return false; }
  2321. function argumentsToArray() {
  2322. var len = arguments.length, args = new Array(len);
  2323. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2324. return args;
  2325. }
  2326. var CombineLatestObservable = (function(__super__) {
  2327. inherits(CombineLatestObservable, __super__);
  2328. function CombineLatestObservable(params, cb) {
  2329. this._params = params;
  2330. this._cb = cb;
  2331. __super__.call(this);
  2332. }
  2333. CombineLatestObservable.prototype.subscribeCore = function(observer) {
  2334. var len = this._params.length,
  2335. subscriptions = new Array(len);
  2336. var state = {
  2337. hasValue: arrayInitialize(len, falseFactory),
  2338. hasValueAll: false,
  2339. isDone: arrayInitialize(len, falseFactory),
  2340. values: new Array(len)
  2341. };
  2342. for (var i = 0; i < len; i++) {
  2343. var source = this._params[i], sad = new SingleAssignmentDisposable();
  2344. subscriptions[i] = sad;
  2345. isPromise(source) && (source = observableFromPromise(source));
  2346. sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this._cb, state)));
  2347. }
  2348. return new NAryDisposable(subscriptions);
  2349. };
  2350. return CombineLatestObservable;
  2351. }(ObservableBase));
  2352. var CombineLatestObserver = (function (__super__) {
  2353. inherits(CombineLatestObserver, __super__);
  2354. function CombineLatestObserver(o, i, cb, state) {
  2355. this._o = o;
  2356. this._i = i;
  2357. this._cb = cb;
  2358. this._state = state;
  2359. __super__.call(this);
  2360. }
  2361. function notTheSame(i) {
  2362. return function (x, j) {
  2363. return j !== i;
  2364. };
  2365. }
  2366. CombineLatestObserver.prototype.next = function (x) {
  2367. this._state.values[this._i] = x;
  2368. this._state.hasValue[this._i] = true;
  2369. if (this._state.hasValueAll || (this._state.hasValueAll = this._state.hasValue.every(identity))) {
  2370. var res = tryCatch(this._cb).apply(null, this._state.values);
  2371. if (res === errorObj) { return this._o.onError(res.e); }
  2372. this._o.onNext(res);
  2373. } else if (this._state.isDone.filter(notTheSame(this._i)).every(identity)) {
  2374. this._o.onCompleted();
  2375. }
  2376. };
  2377. CombineLatestObserver.prototype.error = function (e) {
  2378. this._o.onError(e);
  2379. };
  2380. CombineLatestObserver.prototype.completed = function () {
  2381. this._state.isDone[this._i] = true;
  2382. this._state.isDone.every(identity) && this._o.onCompleted();
  2383. };
  2384. return CombineLatestObserver;
  2385. }(AbstractObserver));
  2386. /**
  2387. * 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.
  2388. *
  2389. * @example
  2390. * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
  2391. * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
  2392. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  2393. */
  2394. var combineLatest = Observable.combineLatest = function () {
  2395. var len = arguments.length, args = new Array(len);
  2396. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2397. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  2398. Array.isArray(args[0]) && (args = args[0]);
  2399. return new CombineLatestObservable(args, resultSelector);
  2400. };
  2401. /**
  2402. * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
  2403. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
  2404. */
  2405. observableProto.concat = function () {
  2406. for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
  2407. args.unshift(this);
  2408. return observableConcat.apply(null, args);
  2409. };
  2410. var ConcatObserver = (function(__super__) {
  2411. inherits(ConcatObserver, __super__);
  2412. function ConcatObserver(s, fn) {
  2413. this._s = s;
  2414. this._fn = fn;
  2415. __super__.call(this);
  2416. }
  2417. ConcatObserver.prototype.next = function (x) { this._s.o.onNext(x); };
  2418. ConcatObserver.prototype.error = function (e) { this._s.o.onError(e); };
  2419. ConcatObserver.prototype.completed = function () { this._s.i++; this._fn(this._s); };
  2420. return ConcatObserver;
  2421. }(AbstractObserver));
  2422. var ConcatObservable = (function(__super__) {
  2423. inherits(ConcatObservable, __super__);
  2424. function ConcatObservable(sources) {
  2425. this._sources = sources;
  2426. __super__.call(this);
  2427. }
  2428. function scheduleRecursive (state, recurse) {
  2429. if (state.disposable.isDisposed) { return; }
  2430. if (state.i === state.sources.length) { return state.o.onCompleted(); }
  2431. // Check if promise
  2432. var currentValue = state.sources[state.i];
  2433. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  2434. var d = new SingleAssignmentDisposable();
  2435. state.subscription.setDisposable(d);
  2436. d.setDisposable(currentValue.subscribe(new ConcatObserver(state, recurse)));
  2437. }
  2438. ConcatObservable.prototype.subscribeCore = function(o) {
  2439. var subscription = new SerialDisposable();
  2440. var disposable = disposableCreate(noop);
  2441. var state = {
  2442. o: o,
  2443. i: 0,
  2444. subscription: subscription,
  2445. disposable: disposable,
  2446. sources: this._sources
  2447. };
  2448. var cancelable = immediateScheduler.scheduleRecursive(state, scheduleRecursive);
  2449. return new NAryDisposable([subscription, disposable, cancelable]);
  2450. };
  2451. return ConcatObservable;
  2452. }(ObservableBase));
  2453. /**
  2454. * Concatenates all the observable sequences.
  2455. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
  2456. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
  2457. */
  2458. var observableConcat = Observable.concat = function () {
  2459. var args;
  2460. if (Array.isArray(arguments[0])) {
  2461. args = arguments[0];
  2462. } else {
  2463. args = new Array(arguments.length);
  2464. for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
  2465. }
  2466. return new ConcatObservable(args);
  2467. };
  2468. /**
  2469. * Concatenates an observable sequence of observable sequences.
  2470. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
  2471. */
  2472. observableProto.concatAll = function () {
  2473. return this.merge(1);
  2474. };
  2475. var MergeObservable = (function (__super__) {
  2476. inherits(MergeObservable, __super__);
  2477. function MergeObservable(source, maxConcurrent) {
  2478. this.source = source;
  2479. this.maxConcurrent = maxConcurrent;
  2480. __super__.call(this);
  2481. }
  2482. MergeObservable.prototype.subscribeCore = function(observer) {
  2483. var g = new CompositeDisposable();
  2484. g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
  2485. return g;
  2486. };
  2487. return MergeObservable;
  2488. }(ObservableBase));
  2489. var MergeObserver = (function (__super__) {
  2490. function MergeObserver(o, max, g) {
  2491. this.o = o;
  2492. this.max = max;
  2493. this.g = g;
  2494. this.done = false;
  2495. this.q = [];
  2496. this.activeCount = 0;
  2497. __super__.call(this);
  2498. }
  2499. inherits(MergeObserver, __super__);
  2500. MergeObserver.prototype.handleSubscribe = function (xs) {
  2501. var sad = new SingleAssignmentDisposable();
  2502. this.g.add(sad);
  2503. isPromise(xs) && (xs = observableFromPromise(xs));
  2504. sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
  2505. };
  2506. MergeObserver.prototype.next = function (innerSource) {
  2507. if(this.activeCount < this.max) {
  2508. this.activeCount++;
  2509. this.handleSubscribe(innerSource);
  2510. } else {
  2511. this.q.push(innerSource);
  2512. }
  2513. };
  2514. MergeObserver.prototype.error = function (e) { this.o.onError(e); };
  2515. MergeObserver.prototype.completed = function () { this.done = true; this.activeCount === 0 && this.o.onCompleted(); };
  2516. function InnerObserver(parent, sad) {
  2517. this.parent = parent;
  2518. this.sad = sad;
  2519. __super__.call(this);
  2520. }
  2521. inherits(InnerObserver, __super__);
  2522. InnerObserver.prototype.next = function (x) { this.parent.o.onNext(x); };
  2523. InnerObserver.prototype.error = function (e) { this.parent.o.onError(e); };
  2524. InnerObserver.prototype.completed = function () {
  2525. this.parent.g.remove(this.sad);
  2526. if (this.parent.q.length > 0) {
  2527. this.parent.handleSubscribe(this.parent.q.shift());
  2528. } else {
  2529. this.parent.activeCount--;
  2530. this.parent.done && this.parent.activeCount === 0 && this.parent.o.onCompleted();
  2531. }
  2532. };
  2533. return MergeObserver;
  2534. }(AbstractObserver));
  2535. /**
  2536. * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
  2537. * Or merges two observable sequences into a single observable sequence.
  2538. * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
  2539. * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
  2540. */
  2541. observableProto.merge = function (maxConcurrentOrOther) {
  2542. return typeof maxConcurrentOrOther !== 'number' ?
  2543. observableMerge(this, maxConcurrentOrOther) :
  2544. new MergeObservable(this, maxConcurrentOrOther);
  2545. };
  2546. /**
  2547. * Merges all the observable sequences into a single observable sequence.
  2548. * The scheduler is optional and if not specified, the immediate scheduler is used.
  2549. * @returns {Observable} The observable sequence that merges the elements of the observable sequences.
  2550. */
  2551. var observableMerge = Observable.merge = function () {
  2552. var scheduler, sources = [], i, len = arguments.length;
  2553. if (!arguments[0]) {
  2554. scheduler = immediateScheduler;
  2555. for(i = 1; i < len; i++) { sources.push(arguments[i]); }
  2556. } else if (isScheduler(arguments[0])) {
  2557. scheduler = arguments[0];
  2558. for(i = 1; i < len; i++) { sources.push(arguments[i]); }
  2559. } else {
  2560. scheduler = immediateScheduler;
  2561. for(i = 0; i < len; i++) { sources.push(arguments[i]); }
  2562. }
  2563. if (Array.isArray(sources[0])) {
  2564. sources = sources[0];
  2565. }
  2566. return observableOf(scheduler, sources).mergeAll();
  2567. };
  2568. var CompositeError = Rx.CompositeError = function(errors) {
  2569. this.innerErrors = errors;
  2570. this.message = 'This contains multiple errors. Check the innerErrors';
  2571. Error.call(this);
  2572. };
  2573. CompositeError.prototype = Object.create(Error.prototype);
  2574. CompositeError.prototype.name = 'CompositeError';
  2575. var MergeDelayErrorObservable = (function(__super__) {
  2576. inherits(MergeDelayErrorObservable, __super__);
  2577. function MergeDelayErrorObservable(source) {
  2578. this.source = source;
  2579. __super__.call(this);
  2580. }
  2581. MergeDelayErrorObservable.prototype.subscribeCore = function (o) {
  2582. var group = new CompositeDisposable(),
  2583. m = new SingleAssignmentDisposable(),
  2584. state = { isStopped: false, errors: [], o: o };
  2585. group.add(m);
  2586. m.setDisposable(this.source.subscribe(new MergeDelayErrorObserver(group, state)));
  2587. return group;
  2588. };
  2589. return MergeDelayErrorObservable;
  2590. }(ObservableBase));
  2591. var MergeDelayErrorObserver = (function(__super__) {
  2592. inherits(MergeDelayErrorObserver, __super__);
  2593. function MergeDelayErrorObserver(group, state) {
  2594. this._group = group;
  2595. this._state = state;
  2596. __super__.call(this);
  2597. }
  2598. function setCompletion(o, errors) {
  2599. if (errors.length === 0) {
  2600. o.onCompleted();
  2601. } else if (errors.length === 1) {
  2602. o.onError(errors[0]);
  2603. } else {
  2604. o.onError(new CompositeError(errors));
  2605. }
  2606. }
  2607. MergeDelayErrorObserver.prototype.next = function (x) {
  2608. var inner = new SingleAssignmentDisposable();
  2609. this._group.add(inner);
  2610. // Check for promises support
  2611. isPromise(x) && (x = observableFromPromise(x));
  2612. inner.setDisposable(x.subscribe(new InnerObserver(inner, this._group, this._state)));
  2613. };
  2614. MergeDelayErrorObserver.prototype.error = function (e) {
  2615. this._state.errors.push(e);
  2616. this._state.isStopped = true;
  2617. this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  2618. };
  2619. MergeDelayErrorObserver.prototype.completed = function () {
  2620. this._state.isStopped = true;
  2621. this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  2622. };
  2623. inherits(InnerObserver, __super__);
  2624. function InnerObserver(inner, group, state) {
  2625. this._inner = inner;
  2626. this._group = group;
  2627. this._state = state;
  2628. __super__.call(this);
  2629. }
  2630. InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  2631. InnerObserver.prototype.error = function (e) {
  2632. this._state.errors.push(e);
  2633. this._group.remove(this._inner);
  2634. this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  2635. };
  2636. InnerObserver.prototype.completed = function () {
  2637. this._group.remove(this._inner);
  2638. this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
  2639. };
  2640. return MergeDelayErrorObserver;
  2641. }(AbstractObserver));
  2642. /**
  2643. * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
  2644. * receive all successfully emitted items from all of the source Observables without being interrupted by
  2645. * an error notification from one of them.
  2646. *
  2647. * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
  2648. * error via the Observer's onError, mergeDelayError will refrain from propagating that
  2649. * error notification until all of the merged Observables have finished emitting items.
  2650. * @param {Array | Arguments} args Arguments or an array to merge.
  2651. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
  2652. */
  2653. Observable.mergeDelayError = function() {
  2654. var args;
  2655. if (Array.isArray(arguments[0])) {
  2656. args = arguments[0];
  2657. } else {
  2658. var len = arguments.length;
  2659. args = new Array(len);
  2660. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2661. }
  2662. var source = observableOf(null, args);
  2663. return new MergeDelayErrorObservable(source);
  2664. };
  2665. var MergeAllObservable = (function (__super__) {
  2666. inherits(MergeAllObservable, __super__);
  2667. function MergeAllObservable(source) {
  2668. this.source = source;
  2669. __super__.call(this);
  2670. }
  2671. MergeAllObservable.prototype.subscribeCore = function (o) {
  2672. var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
  2673. g.add(m);
  2674. m.setDisposable(this.source.subscribe(new MergeAllObserver(o, g)));
  2675. return g;
  2676. };
  2677. return MergeAllObservable;
  2678. }(ObservableBase));
  2679. var MergeAllObserver = (function (__super__) {
  2680. function MergeAllObserver(o, g) {
  2681. this.o = o;
  2682. this.g = g;
  2683. this.done = false;
  2684. __super__.call(this);
  2685. }
  2686. inherits(MergeAllObserver, __super__);
  2687. MergeAllObserver.prototype.next = function(innerSource) {
  2688. var sad = new SingleAssignmentDisposable();
  2689. this.g.add(sad);
  2690. isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
  2691. sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad)));
  2692. };
  2693. MergeAllObserver.prototype.error = function (e) {
  2694. this.o.onError(e);
  2695. };
  2696. MergeAllObserver.prototype.completed = function () {
  2697. this.done = true;
  2698. this.g.length === 1 && this.o.onCompleted();
  2699. };
  2700. function InnerObserver(parent, sad) {
  2701. this.parent = parent;
  2702. this.sad = sad;
  2703. __super__.call(this);
  2704. }
  2705. inherits(InnerObserver, __super__);
  2706. InnerObserver.prototype.next = function (x) {
  2707. this.parent.o.onNext(x);
  2708. };
  2709. InnerObserver.prototype.error = function (e) {
  2710. this.parent.o.onError(e);
  2711. };
  2712. InnerObserver.prototype.completed = function () {
  2713. this.parent.g.remove(this.sad);
  2714. this.parent.done && this.parent.g.length === 1 && this.parent.o.onCompleted();
  2715. };
  2716. return MergeAllObserver;
  2717. }(AbstractObserver));
  2718. /**
  2719. * Merges an observable sequence of observable sequences into an observable sequence.
  2720. * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
  2721. */
  2722. observableProto.mergeAll = function () {
  2723. return new MergeAllObservable(this);
  2724. };
  2725. var SkipUntilObservable = (function(__super__) {
  2726. inherits(SkipUntilObservable, __super__);
  2727. function SkipUntilObservable(source, other) {
  2728. this._s = source;
  2729. this._o = isPromise(other) ? observableFromPromise(other) : other;
  2730. this._open = false;
  2731. __super__.call(this);
  2732. }
  2733. SkipUntilObservable.prototype.subscribeCore = function(o) {
  2734. var leftSubscription = new SingleAssignmentDisposable();
  2735. leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this)));
  2736. isPromise(this._o) && (this._o = observableFromPromise(this._o));
  2737. var rightSubscription = new SingleAssignmentDisposable();
  2738. rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription)));
  2739. return new BinaryDisposable(leftSubscription, rightSubscription);
  2740. };
  2741. return SkipUntilObservable;
  2742. }(ObservableBase));
  2743. var SkipUntilSourceObserver = (function(__super__) {
  2744. inherits(SkipUntilSourceObserver, __super__);
  2745. function SkipUntilSourceObserver(o, p) {
  2746. this._o = o;
  2747. this._p = p;
  2748. __super__.call(this);
  2749. }
  2750. SkipUntilSourceObserver.prototype.next = function (x) {
  2751. this._p._open && this._o.onNext(x);
  2752. };
  2753. SkipUntilSourceObserver.prototype.error = function (err) {
  2754. this._o.onError(err);
  2755. };
  2756. SkipUntilSourceObserver.prototype.onCompleted = function () {
  2757. this._p._open && this._o.onCompleted();
  2758. };
  2759. return SkipUntilSourceObserver;
  2760. }(AbstractObserver));
  2761. var SkipUntilOtherObserver = (function(__super__) {
  2762. inherits(SkipUntilOtherObserver, __super__);
  2763. function SkipUntilOtherObserver(o, p, r) {
  2764. this._o = o;
  2765. this._p = p;
  2766. this._r = r;
  2767. __super__.call(this);
  2768. }
  2769. SkipUntilOtherObserver.prototype.next = function () {
  2770. this._p._open = true;
  2771. this._r.dispose();
  2772. };
  2773. SkipUntilOtherObserver.prototype.error = function (err) {
  2774. this._o.onError(err);
  2775. };
  2776. SkipUntilOtherObserver.prototype.onCompleted = function () {
  2777. this._r.dispose();
  2778. };
  2779. return SkipUntilOtherObserver;
  2780. }(AbstractObserver));
  2781. /**
  2782. * Returns the values from the source observable sequence only after the other observable sequence produces a value.
  2783. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
  2784. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
  2785. */
  2786. observableProto.skipUntil = function (other) {
  2787. return new SkipUntilObservable(this, other);
  2788. };
  2789. var SwitchObservable = (function(__super__) {
  2790. inherits(SwitchObservable, __super__);
  2791. function SwitchObservable(source) {
  2792. this.source = source;
  2793. __super__.call(this);
  2794. }
  2795. SwitchObservable.prototype.subscribeCore = function (o) {
  2796. var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
  2797. return new BinaryDisposable(s, inner);
  2798. };
  2799. inherits(SwitchObserver, AbstractObserver);
  2800. function SwitchObserver(o, inner) {
  2801. this.o = o;
  2802. this.inner = inner;
  2803. this.stopped = false;
  2804. this.latest = 0;
  2805. this.hasLatest = false;
  2806. AbstractObserver.call(this);
  2807. }
  2808. SwitchObserver.prototype.next = function (innerSource) {
  2809. var d = new SingleAssignmentDisposable(), id = ++this.latest;
  2810. this.hasLatest = true;
  2811. this.inner.setDisposable(d);
  2812. isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
  2813. d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
  2814. };
  2815. SwitchObserver.prototype.error = function (e) {
  2816. this.o.onError(e);
  2817. };
  2818. SwitchObserver.prototype.completed = function () {
  2819. this.stopped = true;
  2820. !this.hasLatest && this.o.onCompleted();
  2821. };
  2822. inherits(InnerObserver, AbstractObserver);
  2823. function InnerObserver(parent, id) {
  2824. this.parent = parent;
  2825. this.id = id;
  2826. AbstractObserver.call(this);
  2827. }
  2828. InnerObserver.prototype.next = function (x) {
  2829. this.parent.latest === this.id && this.parent.o.onNext(x);
  2830. };
  2831. InnerObserver.prototype.error = function (e) {
  2832. this.parent.latest === this.id && this.parent.o.onError(e);
  2833. };
  2834. InnerObserver.prototype.completed = function () {
  2835. if (this.parent.latest === this.id) {
  2836. this.parent.hasLatest = false;
  2837. this.parent.stopped && this.parent.o.onCompleted();
  2838. }
  2839. };
  2840. return SwitchObservable;
  2841. }(ObservableBase));
  2842. /**
  2843. * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
  2844. * @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.
  2845. */
  2846. observableProto['switch'] = observableProto.switchLatest = function () {
  2847. return new SwitchObservable(this);
  2848. };
  2849. var TakeUntilObservable = (function(__super__) {
  2850. inherits(TakeUntilObservable, __super__);
  2851. function TakeUntilObservable(source, other) {
  2852. this.source = source;
  2853. this.other = isPromise(other) ? observableFromPromise(other) : other;
  2854. __super__.call(this);
  2855. }
  2856. TakeUntilObservable.prototype.subscribeCore = function(o) {
  2857. return new BinaryDisposable(
  2858. this.source.subscribe(o),
  2859. this.other.subscribe(new TakeUntilObserver(o))
  2860. );
  2861. };
  2862. return TakeUntilObservable;
  2863. }(ObservableBase));
  2864. var TakeUntilObserver = (function(__super__) {
  2865. inherits(TakeUntilObserver, __super__);
  2866. function TakeUntilObserver(o) {
  2867. this._o = o;
  2868. __super__.call(this);
  2869. }
  2870. TakeUntilObserver.prototype.next = function () {
  2871. this._o.onCompleted();
  2872. };
  2873. TakeUntilObserver.prototype.error = function (err) {
  2874. this._o.onError(err);
  2875. };
  2876. TakeUntilObserver.prototype.onCompleted = noop;
  2877. return TakeUntilObserver;
  2878. }(AbstractObserver));
  2879. /**
  2880. * Returns the values from the source observable sequence until the other observable sequence produces a value.
  2881. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
  2882. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
  2883. */
  2884. observableProto.takeUntil = function (other) {
  2885. return new TakeUntilObservable(this, other);
  2886. };
  2887. function falseFactory() { return false; }
  2888. function argumentsToArray() {
  2889. var len = arguments.length, args = new Array(len);
  2890. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2891. return args;
  2892. }
  2893. var WithLatestFromObservable = (function(__super__) {
  2894. inherits(WithLatestFromObservable, __super__);
  2895. function WithLatestFromObservable(source, sources, resultSelector) {
  2896. this._s = source;
  2897. this._ss = sources;
  2898. this._cb = resultSelector;
  2899. __super__.call(this);
  2900. }
  2901. WithLatestFromObservable.prototype.subscribeCore = function (o) {
  2902. var len = this._ss.length;
  2903. var state = {
  2904. hasValue: arrayInitialize(len, falseFactory),
  2905. hasValueAll: false,
  2906. values: new Array(len)
  2907. };
  2908. var n = this._ss.length, subscriptions = new Array(n + 1);
  2909. for (var i = 0; i < n; i++) {
  2910. var other = this._ss[i], sad = new SingleAssignmentDisposable();
  2911. isPromise(other) && (other = observableFromPromise(other));
  2912. sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, state)));
  2913. subscriptions[i] = sad;
  2914. }
  2915. var outerSad = new SingleAssignmentDisposable();
  2916. outerSad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this._cb, state)));
  2917. subscriptions[n] = outerSad;
  2918. return new NAryDisposable(subscriptions);
  2919. };
  2920. return WithLatestFromObservable;
  2921. }(ObservableBase));
  2922. var WithLatestFromOtherObserver = (function (__super__) {
  2923. inherits(WithLatestFromOtherObserver, __super__);
  2924. function WithLatestFromOtherObserver(o, i, state) {
  2925. this._o = o;
  2926. this._i = i;
  2927. this._state = state;
  2928. __super__.call(this);
  2929. }
  2930. WithLatestFromOtherObserver.prototype.next = function (x) {
  2931. this._state.values[this._i] = x;
  2932. this._state.hasValue[this._i] = true;
  2933. this._state.hasValueAll = this._state.hasValue.every(identity);
  2934. };
  2935. WithLatestFromOtherObserver.prototype.error = function (e) {
  2936. this._o.onError(e);
  2937. };
  2938. WithLatestFromOtherObserver.prototype.completed = noop;
  2939. return WithLatestFromOtherObserver;
  2940. }(AbstractObserver));
  2941. var WithLatestFromSourceObserver = (function (__super__) {
  2942. inherits(WithLatestFromSourceObserver, __super__);
  2943. function WithLatestFromSourceObserver(o, cb, state) {
  2944. this._o = o;
  2945. this._cb = cb;
  2946. this._state = state;
  2947. __super__.call(this);
  2948. }
  2949. WithLatestFromSourceObserver.prototype.next = function (x) {
  2950. var allValues = [x].concat(this._state.values);
  2951. if (!this._state.hasValueAll) { return; }
  2952. var res = tryCatch(this._cb).apply(null, allValues);
  2953. if (res === errorObj) { return this._o.onError(res.e); }
  2954. this._o.onNext(res);
  2955. };
  2956. WithLatestFromSourceObserver.prototype.error = function (e) {
  2957. this._o.onError(e);
  2958. };
  2959. WithLatestFromSourceObserver.prototype.completed = function () {
  2960. this._o.onCompleted();
  2961. };
  2962. return WithLatestFromSourceObserver;
  2963. }(AbstractObserver));
  2964. /**
  2965. * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
  2966. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  2967. */
  2968. observableProto.withLatestFrom = function () {
  2969. if (arguments.length === 0) { throw new Error('invalid arguments'); }
  2970. var len = arguments.length, args = new Array(len);
  2971. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  2972. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  2973. Array.isArray(args[0]) && (args = args[0]);
  2974. return new WithLatestFromObservable(this, args, resultSelector);
  2975. };
  2976. function falseFactory() { return false; }
  2977. function emptyArrayFactory() { return []; }
  2978. var ZipObservable = (function(__super__) {
  2979. inherits(ZipObservable, __super__);
  2980. function ZipObservable(sources, resultSelector) {
  2981. this._s = sources;
  2982. this._cb = resultSelector;
  2983. __super__.call(this);
  2984. }
  2985. ZipObservable.prototype.subscribeCore = function(observer) {
  2986. var n = this._s.length,
  2987. subscriptions = new Array(n),
  2988. done = arrayInitialize(n, falseFactory),
  2989. q = arrayInitialize(n, emptyArrayFactory);
  2990. for (var i = 0; i < n; i++) {
  2991. var source = this._s[i], sad = new SingleAssignmentDisposable();
  2992. subscriptions[i] = sad;
  2993. isPromise(source) && (source = observableFromPromise(source));
  2994. sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this, q, done)));
  2995. }
  2996. return new NAryDisposable(subscriptions);
  2997. };
  2998. return ZipObservable;
  2999. }(ObservableBase));
  3000. var ZipObserver = (function (__super__) {
  3001. inherits(ZipObserver, __super__);
  3002. function ZipObserver(o, i, p, q, d) {
  3003. this._o = o;
  3004. this._i = i;
  3005. this._p = p;
  3006. this._q = q;
  3007. this._d = d;
  3008. __super__.call(this);
  3009. }
  3010. function notEmpty(x) { return x.length > 0; }
  3011. function shiftEach(x) { return x.shift(); }
  3012. function notTheSame(i) {
  3013. return function (x, j) {
  3014. return j !== i;
  3015. };
  3016. }
  3017. ZipObserver.prototype.next = function (x) {
  3018. this._q[this._i].push(x);
  3019. if (this._q.every(notEmpty)) {
  3020. var queuedValues = this._q.map(shiftEach);
  3021. var res = tryCatch(this._p._cb).apply(null, queuedValues);
  3022. if (res === errorObj) { return this._o.onError(res.e); }
  3023. this._o.onNext(res);
  3024. } else if (this._d.filter(notTheSame(this._i)).every(identity)) {
  3025. this._o.onCompleted();
  3026. }
  3027. };
  3028. ZipObserver.prototype.error = function (e) {
  3029. this._o.onError(e);
  3030. };
  3031. ZipObserver.prototype.completed = function () {
  3032. this._d[this._i] = true;
  3033. this._d.every(identity) && this._o.onCompleted();
  3034. };
  3035. return ZipObserver;
  3036. }(AbstractObserver));
  3037. /**
  3038. * 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.
  3039. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
  3040. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
  3041. */
  3042. observableProto.zip = function () {
  3043. if (arguments.length === 0) { throw new Error('invalid arguments'); }
  3044. var len = arguments.length, args = new Array(len);
  3045. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3046. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  3047. Array.isArray(args[0]) && (args = args[0]);
  3048. var parent = this;
  3049. args.unshift(parent);
  3050. return new ZipObservable(args, resultSelector);
  3051. };
  3052. /**
  3053. * 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.
  3054. * @param arguments Observable sources.
  3055. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
  3056. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  3057. */
  3058. Observable.zip = function () {
  3059. var len = arguments.length, args = new Array(len);
  3060. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3061. if (Array.isArray(args[0])) {
  3062. args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0];
  3063. }
  3064. var first = args.shift();
  3065. return first.zip.apply(first, args);
  3066. };
  3067. function falseFactory() { return false; }
  3068. function emptyArrayFactory() { return []; }
  3069. function argumentsToArray() {
  3070. var len = arguments.length, args = new Array(len);
  3071. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3072. return args;
  3073. }
  3074. var ZipIterableObservable = (function(__super__) {
  3075. inherits(ZipIterableObservable, __super__);
  3076. function ZipIterableObservable(sources, cb) {
  3077. this.sources = sources;
  3078. this._cb = cb;
  3079. __super__.call(this);
  3080. }
  3081. ZipIterableObservable.prototype.subscribeCore = function (o) {
  3082. var sources = this.sources, len = sources.length, subscriptions = new Array(len);
  3083. var state = {
  3084. q: arrayInitialize(len, emptyArrayFactory),
  3085. done: arrayInitialize(len, falseFactory),
  3086. cb: this._cb,
  3087. o: o
  3088. };
  3089. for (var i = 0; i < len; i++) {
  3090. (function (i) {
  3091. var source = sources[i], sad = new SingleAssignmentDisposable();
  3092. (isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));
  3093. subscriptions[i] = sad;
  3094. sad.setDisposable(source.subscribe(new ZipIterableObserver(state, i)));
  3095. }(i));
  3096. }
  3097. return new NAryDisposable(subscriptions);
  3098. };
  3099. return ZipIterableObservable;
  3100. }(ObservableBase));
  3101. var ZipIterableObserver = (function (__super__) {
  3102. inherits(ZipIterableObserver, __super__);
  3103. function ZipIterableObserver(s, i) {
  3104. this._s = s;
  3105. this._i = i;
  3106. __super__.call(this);
  3107. }
  3108. function notEmpty(x) { return x.length > 0; }
  3109. function shiftEach(x) { return x.shift(); }
  3110. function notTheSame(i) {
  3111. return function (x, j) {
  3112. return j !== i;
  3113. };
  3114. }
  3115. ZipIterableObserver.prototype.next = function (x) {
  3116. this._s.q[this._i].push(x);
  3117. if (this._s.q.every(notEmpty)) {
  3118. var queuedValues = this._s.q.map(shiftEach),
  3119. res = tryCatch(this._s.cb).apply(null, queuedValues);
  3120. if (res === errorObj) { return this._s.o.onError(res.e); }
  3121. this._s.o.onNext(res);
  3122. } else if (this._s.done.filter(notTheSame(this._i)).every(identity)) {
  3123. this._s.o.onCompleted();
  3124. }
  3125. };
  3126. ZipIterableObserver.prototype.error = function (e) { this._s.o.onError(e); };
  3127. ZipIterableObserver.prototype.completed = function () {
  3128. this._s.done[this._i] = true;
  3129. this._s.done.every(identity) && this._s.o.onCompleted();
  3130. };
  3131. return ZipIterableObserver;
  3132. }(AbstractObserver));
  3133. /**
  3134. * 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.
  3135. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
  3136. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
  3137. */
  3138. observableProto.zipIterable = function () {
  3139. if (arguments.length === 0) { throw new Error('invalid arguments'); }
  3140. var len = arguments.length, args = new Array(len);
  3141. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3142. var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
  3143. var parent = this;
  3144. args.unshift(parent);
  3145. return new ZipIterableObservable(args, resultSelector);
  3146. };
  3147. function asObservable(source) {
  3148. return function subscribe(o) { return source.subscribe(o); };
  3149. }
  3150. /**
  3151. * Hides the identity of an observable sequence.
  3152. * @returns {Observable} An observable sequence that hides the identity of the source sequence.
  3153. */
  3154. observableProto.asObservable = function () {
  3155. return new AnonymousObservable(asObservable(this), this);
  3156. };
  3157. var DematerializeObservable = (function (__super__) {
  3158. inherits(DematerializeObservable, __super__);
  3159. function DematerializeObservable(source) {
  3160. this.source = source;
  3161. __super__.call(this);
  3162. }
  3163. DematerializeObservable.prototype.subscribeCore = function (o) {
  3164. return this.source.subscribe(new DematerializeObserver(o));
  3165. };
  3166. return DematerializeObservable;
  3167. }(ObservableBase));
  3168. var DematerializeObserver = (function (__super__) {
  3169. inherits(DematerializeObserver, __super__);
  3170. function DematerializeObserver(o) {
  3171. this._o = o;
  3172. __super__.call(this);
  3173. }
  3174. DematerializeObserver.prototype.next = function (x) { x.accept(this._o); };
  3175. DematerializeObserver.prototype.error = function (e) { this._o.onError(e); };
  3176. DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); };
  3177. return DematerializeObserver;
  3178. }(AbstractObserver));
  3179. /**
  3180. * Dematerializes the explicit notification values of an observable sequence as implicit notifications.
  3181. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
  3182. */
  3183. observableProto.dematerialize = function () {
  3184. return new DematerializeObservable(this);
  3185. };
  3186. var DistinctUntilChangedObservable = (function(__super__) {
  3187. inherits(DistinctUntilChangedObservable, __super__);
  3188. function DistinctUntilChangedObservable(source, keyFn, comparer) {
  3189. this.source = source;
  3190. this.keyFn = keyFn;
  3191. this.comparer = comparer;
  3192. __super__.call(this);
  3193. }
  3194. DistinctUntilChangedObservable.prototype.subscribeCore = function (o) {
  3195. return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer));
  3196. };
  3197. return DistinctUntilChangedObservable;
  3198. }(ObservableBase));
  3199. var DistinctUntilChangedObserver = (function(__super__) {
  3200. inherits(DistinctUntilChangedObserver, __super__);
  3201. function DistinctUntilChangedObserver(o, keyFn, comparer) {
  3202. this.o = o;
  3203. this.keyFn = keyFn;
  3204. this.comparer = comparer;
  3205. this.hasCurrentKey = false;
  3206. this.currentKey = null;
  3207. __super__.call(this);
  3208. }
  3209. DistinctUntilChangedObserver.prototype.next = function (x) {
  3210. var key = x, comparerEquals;
  3211. if (isFunction(this.keyFn)) {
  3212. key = tryCatch(this.keyFn)(x);
  3213. if (key === errorObj) { return this.o.onError(key.e); }
  3214. }
  3215. if (this.hasCurrentKey) {
  3216. comparerEquals = tryCatch(this.comparer)(this.currentKey, key);
  3217. if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); }
  3218. }
  3219. if (!this.hasCurrentKey || !comparerEquals) {
  3220. this.hasCurrentKey = true;
  3221. this.currentKey = key;
  3222. this.o.onNext(x);
  3223. }
  3224. };
  3225. DistinctUntilChangedObserver.prototype.error = function(e) {
  3226. this.o.onError(e);
  3227. };
  3228. DistinctUntilChangedObserver.prototype.completed = function () {
  3229. this.o.onCompleted();
  3230. };
  3231. return DistinctUntilChangedObserver;
  3232. }(AbstractObserver));
  3233. /**
  3234. * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer.
  3235. * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value.
  3236. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
  3237. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
  3238. */
  3239. observableProto.distinctUntilChanged = function (keyFn, comparer) {
  3240. comparer || (comparer = defaultComparer);
  3241. return new DistinctUntilChangedObservable(this, keyFn, comparer);
  3242. };
  3243. var TapObservable = (function(__super__) {
  3244. inherits(TapObservable,__super__);
  3245. function TapObservable(source, observerOrOnNext, onError, onCompleted) {
  3246. this.source = source;
  3247. this._oN = observerOrOnNext;
  3248. this._oE = onError;
  3249. this._oC = onCompleted;
  3250. __super__.call(this);
  3251. }
  3252. TapObservable.prototype.subscribeCore = function(o) {
  3253. return this.source.subscribe(new InnerObserver(o, this));
  3254. };
  3255. inherits(InnerObserver, AbstractObserver);
  3256. function InnerObserver(o, p) {
  3257. this.o = o;
  3258. this.t = !p._oN || isFunction(p._oN) ?
  3259. observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) :
  3260. p._oN;
  3261. this.isStopped = false;
  3262. AbstractObserver.call(this);
  3263. }
  3264. InnerObserver.prototype.next = function(x) {
  3265. var res = tryCatch(this.t.onNext).call(this.t, x);
  3266. if (res === errorObj) { this.o.onError(res.e); }
  3267. this.o.onNext(x);
  3268. };
  3269. InnerObserver.prototype.error = function(err) {
  3270. var res = tryCatch(this.t.onError).call(this.t, err);
  3271. if (res === errorObj) { return this.o.onError(res.e); }
  3272. this.o.onError(err);
  3273. };
  3274. InnerObserver.prototype.completed = function() {
  3275. var res = tryCatch(this.t.onCompleted).call(this.t);
  3276. if (res === errorObj) { return this.o.onError(res.e); }
  3277. this.o.onCompleted();
  3278. };
  3279. return TapObservable;
  3280. }(ObservableBase));
  3281. /**
  3282. * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
  3283. * 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.
  3284. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
  3285. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
  3286. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
  3287. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3288. */
  3289. observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
  3290. return new TapObservable(this, observerOrOnNext, onError, onCompleted);
  3291. };
  3292. /**
  3293. * Invokes an action for each element in the observable sequence.
  3294. * 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.
  3295. * @param {Function} onNext Action to invoke for each element in the observable sequence.
  3296. * @param {Any} [thisArg] Object to use as this when executing callback.
  3297. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3298. */
  3299. observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
  3300. return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
  3301. };
  3302. /**
  3303. * Invokes an action upon exceptional termination of the observable sequence.
  3304. * 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.
  3305. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
  3306. * @param {Any} [thisArg] Object to use as this when executing callback.
  3307. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3308. */
  3309. observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
  3310. return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
  3311. };
  3312. /**
  3313. * Invokes an action upon graceful termination of the observable sequence.
  3314. * 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.
  3315. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
  3316. * @param {Any} [thisArg] Object to use as this when executing callback.
  3317. * @returns {Observable} The source sequence with the side-effecting behavior applied.
  3318. */
  3319. observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
  3320. return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
  3321. };
  3322. var FinallyObservable = (function (__super__) {
  3323. inherits(FinallyObservable, __super__);
  3324. function FinallyObservable(source, fn, thisArg) {
  3325. this.source = source;
  3326. this._fn = bindCallback(fn, thisArg, 0);
  3327. __super__.call(this);
  3328. }
  3329. FinallyObservable.prototype.subscribeCore = function (o) {
  3330. var d = tryCatch(this.source.subscribe).call(this.source, o);
  3331. if (d === errorObj) {
  3332. this._fn();
  3333. thrower(d.e);
  3334. }
  3335. return new FinallyDisposable(d, this._fn);
  3336. };
  3337. function FinallyDisposable(s, fn) {
  3338. this.isDisposed = false;
  3339. this._s = s;
  3340. this._fn = fn;
  3341. }
  3342. FinallyDisposable.prototype.dispose = function () {
  3343. if (!this.isDisposed) {
  3344. var res = tryCatch(this._s.dispose).call(this._s);
  3345. this._fn();
  3346. res === errorObj && thrower(res.e);
  3347. }
  3348. };
  3349. return FinallyObservable;
  3350. }(ObservableBase));
  3351. /**
  3352. * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
  3353. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
  3354. * @returns {Observable} Source sequence with the action-invoking termination behavior applied.
  3355. */
  3356. observableProto['finally'] = function (action, thisArg) {
  3357. return new FinallyObservable(this, action, thisArg);
  3358. };
  3359. var IgnoreElementsObservable = (function(__super__) {
  3360. inherits(IgnoreElementsObservable, __super__);
  3361. function IgnoreElementsObservable(source) {
  3362. this.source = source;
  3363. __super__.call(this);
  3364. }
  3365. IgnoreElementsObservable.prototype.subscribeCore = function (o) {
  3366. return this.source.subscribe(new InnerObserver(o));
  3367. };
  3368. function InnerObserver(o) {
  3369. this.o = o;
  3370. this.isStopped = false;
  3371. }
  3372. InnerObserver.prototype.onNext = noop;
  3373. InnerObserver.prototype.onError = function (err) {
  3374. if(!this.isStopped) {
  3375. this.isStopped = true;
  3376. this.o.onError(err);
  3377. }
  3378. };
  3379. InnerObserver.prototype.onCompleted = function () {
  3380. if(!this.isStopped) {
  3381. this.isStopped = true;
  3382. this.o.onCompleted();
  3383. }
  3384. };
  3385. InnerObserver.prototype.dispose = function() { this.isStopped = true; };
  3386. InnerObserver.prototype.fail = function (e) {
  3387. if (!this.isStopped) {
  3388. this.isStopped = true;
  3389. this.observer.onError(e);
  3390. return true;
  3391. }
  3392. return false;
  3393. };
  3394. return IgnoreElementsObservable;
  3395. }(ObservableBase));
  3396. /**
  3397. * Ignores all elements in an observable sequence leaving only the termination messages.
  3398. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
  3399. */
  3400. observableProto.ignoreElements = function () {
  3401. return new IgnoreElementsObservable(this);
  3402. };
  3403. var MaterializeObservable = (function (__super__) {
  3404. inherits(MaterializeObservable, __super__);
  3405. function MaterializeObservable(source, fn) {
  3406. this.source = source;
  3407. __super__.call(this);
  3408. }
  3409. MaterializeObservable.prototype.subscribeCore = function (o) {
  3410. return this.source.subscribe(new MaterializeObserver(o));
  3411. };
  3412. return MaterializeObservable;
  3413. }(ObservableBase));
  3414. var MaterializeObserver = (function (__super__) {
  3415. inherits(MaterializeObserver, __super__);
  3416. function MaterializeObserver(o) {
  3417. this._o = o;
  3418. __super__.call(this);
  3419. }
  3420. MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) };
  3421. MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); };
  3422. MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); };
  3423. return MaterializeObserver;
  3424. }(AbstractObserver));
  3425. /**
  3426. * Materializes the implicit notifications of an observable sequence as explicit notification values.
  3427. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
  3428. */
  3429. observableProto.materialize = function () {
  3430. return new MaterializeObservable(this);
  3431. };
  3432. /**
  3433. * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
  3434. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
  3435. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
  3436. */
  3437. observableProto.repeat = function (repeatCount) {
  3438. return enumerableRepeat(this, repeatCount).concat();
  3439. };
  3440. /**
  3441. * 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.
  3442. * Note if you encounter an error and want it to retry once, then you must use .retry(2);
  3443. *
  3444. * @example
  3445. * var res = retried = retry.repeat();
  3446. * var res = retried = retry.repeat(2);
  3447. * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
  3448. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
  3449. */
  3450. observableProto.retry = function (retryCount) {
  3451. return enumerableRepeat(this, retryCount).catchError();
  3452. };
  3453. function repeat(value) {
  3454. return {
  3455. '@@iterator': function () {
  3456. return {
  3457. next: function () {
  3458. return { done: false, value: value };
  3459. }
  3460. };
  3461. }
  3462. };
  3463. }
  3464. var RetryWhenObservable = (function(__super__) {
  3465. function createDisposable(state) {
  3466. return {
  3467. isDisposed: false,
  3468. dispose: function () {
  3469. if (!this.isDisposed) {
  3470. this.isDisposed = true;
  3471. state.isDisposed = true;
  3472. }
  3473. }
  3474. };
  3475. }
  3476. function RetryWhenObservable(source, notifier) {
  3477. this.source = source;
  3478. this._notifier = notifier;
  3479. __super__.call(this);
  3480. }
  3481. inherits(RetryWhenObservable, __super__);
  3482. RetryWhenObservable.prototype.subscribeCore = function (o) {
  3483. var exceptions = new Subject(),
  3484. notifier = new Subject(),
  3485. handled = this._notifier(exceptions),
  3486. notificationDisposable = handled.subscribe(notifier);
  3487. var e = this.source['@@iterator']();
  3488. var state = { isDisposed: false },
  3489. lastError,
  3490. subscription = new SerialDisposable();
  3491. var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) {
  3492. if (state.isDisposed) { return; }
  3493. var currentItem = e.next();
  3494. if (currentItem.done) {
  3495. if (lastError) {
  3496. o.onError(lastError);
  3497. } else {
  3498. o.onCompleted();
  3499. }
  3500. return;
  3501. }
  3502. // Check if promise
  3503. var currentValue = currentItem.value;
  3504. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  3505. var outer = new SingleAssignmentDisposable();
  3506. var inner = new SingleAssignmentDisposable();
  3507. subscription.setDisposable(new BinaryDisposable(inner, outer));
  3508. outer.setDisposable(currentValue.subscribe(
  3509. function(x) { o.onNext(x); },
  3510. function (exn) {
  3511. inner.setDisposable(notifier.subscribe(recurse, function(ex) {
  3512. o.onError(ex);
  3513. }, function() {
  3514. o.onCompleted();
  3515. }));
  3516. exceptions.onNext(exn);
  3517. outer.dispose();
  3518. },
  3519. function() { o.onCompleted(); }));
  3520. });
  3521. return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]);
  3522. };
  3523. return RetryWhenObservable;
  3524. }(ObservableBase));
  3525. observableProto.retryWhen = function (notifier) {
  3526. return new RetryWhenObservable(repeat(this), notifier);
  3527. };
  3528. function repeat(value) {
  3529. return {
  3530. '@@iterator': function () {
  3531. return {
  3532. next: function () {
  3533. return { done: false, value: value };
  3534. }
  3535. };
  3536. }
  3537. };
  3538. }
  3539. var RepeatWhenObservable = (function(__super__) {
  3540. function createDisposable(state) {
  3541. return {
  3542. isDisposed: false,
  3543. dispose: function () {
  3544. if (!this.isDisposed) {
  3545. this.isDisposed = true;
  3546. state.isDisposed = true;
  3547. }
  3548. }
  3549. };
  3550. }
  3551. function RepeatWhenObservable(source, notifier) {
  3552. this.source = source;
  3553. this._notifier = notifier;
  3554. __super__.call(this);
  3555. }
  3556. inherits(RepeatWhenObservable, __super__);
  3557. RepeatWhenObservable.prototype.subscribeCore = function (o) {
  3558. var completions = new Subject(),
  3559. notifier = new Subject(),
  3560. handled = this._notifier(completions),
  3561. notificationDisposable = handled.subscribe(notifier);
  3562. var e = this.source['@@iterator']();
  3563. var state = { isDisposed: false },
  3564. lastError,
  3565. subscription = new SerialDisposable();
  3566. var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) {
  3567. if (state.isDisposed) { return; }
  3568. var currentItem = e.next();
  3569. if (currentItem.done) {
  3570. if (lastError) {
  3571. o.onError(lastError);
  3572. } else {
  3573. o.onCompleted();
  3574. }
  3575. return;
  3576. }
  3577. // Check if promise
  3578. var currentValue = currentItem.value;
  3579. isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
  3580. var outer = new SingleAssignmentDisposable();
  3581. var inner = new SingleAssignmentDisposable();
  3582. subscription.setDisposable(new BinaryDisposable(inner, outer));
  3583. outer.setDisposable(currentValue.subscribe(
  3584. function(x) { o.onNext(x); },
  3585. function (exn) { o.onError(exn); },
  3586. function() {
  3587. inner.setDisposable(notifier.subscribe(recurse, function(ex) {
  3588. o.onError(ex);
  3589. }, function() {
  3590. o.onCompleted();
  3591. }));
  3592. completions.onNext(null);
  3593. outer.dispose();
  3594. }));
  3595. });
  3596. return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]);
  3597. };
  3598. return RepeatWhenObservable;
  3599. }(ObservableBase));
  3600. observableProto.repeatWhen = function (notifier) {
  3601. return new RepeatWhenObservable(repeat(this), notifier);
  3602. };
  3603. var ScanObservable = (function(__super__) {
  3604. inherits(ScanObservable, __super__);
  3605. function ScanObservable(source, accumulator, hasSeed, seed) {
  3606. this.source = source;
  3607. this.accumulator = accumulator;
  3608. this.hasSeed = hasSeed;
  3609. this.seed = seed;
  3610. __super__.call(this);
  3611. }
  3612. ScanObservable.prototype.subscribeCore = function(o) {
  3613. return this.source.subscribe(new ScanObserver(o,this));
  3614. };
  3615. return ScanObservable;
  3616. }(ObservableBase));
  3617. var ScanObserver = (function (__super__) {
  3618. inherits(ScanObserver, __super__);
  3619. function ScanObserver(o, parent) {
  3620. this._o = o;
  3621. this._p = parent;
  3622. this._fn = parent.accumulator;
  3623. this._hs = parent.hasSeed;
  3624. this._s = parent.seed;
  3625. this._ha = false;
  3626. this._a = null;
  3627. this._hv = false;
  3628. this._i = 0;
  3629. __super__.call(this);
  3630. }
  3631. ScanObserver.prototype.next = function (x) {
  3632. !this._hv && (this._hv = true);
  3633. if (this._ha) {
  3634. this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
  3635. } else {
  3636. this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
  3637. this._ha = true;
  3638. }
  3639. if (this._a === errorObj) { return this._o.onError(this._a.e); }
  3640. this._o.onNext(this._a);
  3641. this._i++;
  3642. };
  3643. ScanObserver.prototype.error = function (e) {
  3644. this._o.onError(e);
  3645. };
  3646. ScanObserver.prototype.completed = function () {
  3647. !this._hv && this._hs && this._o.onNext(this._s);
  3648. this._o.onCompleted();
  3649. };
  3650. return ScanObserver;
  3651. }(AbstractObserver));
  3652. /**
  3653. * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
  3654. * For aggregation behavior with no intermediate results, see Observable.aggregate.
  3655. * @param {Mixed} [seed] The initial accumulator value.
  3656. * @param {Function} accumulator An accumulator function to be invoked on each element.
  3657. * @returns {Observable} An observable sequence containing the accumulated values.
  3658. */
  3659. observableProto.scan = function () {
  3660. var hasSeed = false, seed, accumulator = arguments[0];
  3661. if (arguments.length === 2) {
  3662. hasSeed = true;
  3663. seed = arguments[1];
  3664. }
  3665. return new ScanObservable(this, accumulator, hasSeed, seed);
  3666. };
  3667. var SkipLastObservable = (function (__super__) {
  3668. inherits(SkipLastObservable, __super__);
  3669. function SkipLastObservable(source, c) {
  3670. this.source = source;
  3671. this._c = c;
  3672. __super__.call(this);
  3673. }
  3674. SkipLastObservable.prototype.subscribeCore = function (o) {
  3675. return this.source.subscribe(new SkipLastObserver(o, this._c));
  3676. };
  3677. return SkipLastObservable;
  3678. }(ObservableBase));
  3679. var SkipLastObserver = (function (__super__) {
  3680. inherits(SkipLastObserver, __super__);
  3681. function SkipLastObserver(o, c) {
  3682. this._o = o;
  3683. this._c = c;
  3684. this._q = [];
  3685. __super__.call(this);
  3686. }
  3687. SkipLastObserver.prototype.next = function (x) {
  3688. this._q.push(x);
  3689. this._q.length > this._c && this._o.onNext(this._q.shift());
  3690. };
  3691. SkipLastObserver.prototype.error = function (e) {
  3692. this._o.onError(e);
  3693. };
  3694. SkipLastObserver.prototype.completed = function () {
  3695. this._o.onCompleted();
  3696. };
  3697. return SkipLastObserver;
  3698. }(AbstractObserver));
  3699. /**
  3700. * Bypasses a specified number of elements at the end of an observable sequence.
  3701. * @description
  3702. * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
  3703. * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
  3704. * @param count Number of elements to bypass at the end of the source sequence.
  3705. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
  3706. */
  3707. observableProto.skipLast = function (count) {
  3708. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  3709. return new SkipLastObservable(this, count);
  3710. };
  3711. /**
  3712. * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
  3713. * @example
  3714. * var res = source.startWith(1, 2, 3);
  3715. * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
  3716. * @param {Arguments} args The specified values to prepend to the observable sequence
  3717. * @returns {Observable} The source sequence prepended with the specified values.
  3718. */
  3719. observableProto.startWith = function () {
  3720. var values, scheduler, start = 0;
  3721. if (!!arguments.length && isScheduler(arguments[0])) {
  3722. scheduler = arguments[0];
  3723. start = 1;
  3724. } else {
  3725. scheduler = immediateScheduler;
  3726. }
  3727. for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
  3728. return enumerableOf([observableFromArray(args, scheduler), this]).concat();
  3729. };
  3730. var TakeLastObserver = (function (__super__) {
  3731. inherits(TakeLastObserver, __super__);
  3732. function TakeLastObserver(o, c) {
  3733. this._o = o;
  3734. this._c = c;
  3735. this._q = [];
  3736. __super__.call(this);
  3737. }
  3738. TakeLastObserver.prototype.next = function (x) {
  3739. this._q.push(x);
  3740. this._q.length > this._c && this._q.shift();
  3741. };
  3742. TakeLastObserver.prototype.error = function (e) {
  3743. this._o.onError(e);
  3744. };
  3745. TakeLastObserver.prototype.completed = function () {
  3746. while (this._q.length > 0) { this._o.onNext(this._q.shift()); }
  3747. this._o.onCompleted();
  3748. };
  3749. return TakeLastObserver;
  3750. }(AbstractObserver));
  3751. /**
  3752. * Returns a specified number of contiguous elements from the end of an observable sequence.
  3753. * @description
  3754. * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
  3755. * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
  3756. * @param {Number} count Number of elements to take from the end of the source sequence.
  3757. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
  3758. */
  3759. observableProto.takeLast = function (count) {
  3760. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  3761. var source = this;
  3762. return new AnonymousObservable(function (o) {
  3763. return source.subscribe(new TakeLastObserver(o, count));
  3764. }, source);
  3765. };
  3766. observableProto.flatMapConcat = observableProto.concatMap = function(selector, resultSelector, thisArg) {
  3767. return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(1);
  3768. };
  3769. var MapObservable = (function (__super__) {
  3770. inherits(MapObservable, __super__);
  3771. function MapObservable(source, selector, thisArg) {
  3772. this.source = source;
  3773. this.selector = bindCallback(selector, thisArg, 3);
  3774. __super__.call(this);
  3775. }
  3776. function innerMap(selector, self) {
  3777. return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); };
  3778. }
  3779. MapObservable.prototype.internalMap = function (selector, thisArg) {
  3780. return new MapObservable(this.source, innerMap(selector, this), thisArg);
  3781. };
  3782. MapObservable.prototype.subscribeCore = function (o) {
  3783. return this.source.subscribe(new InnerObserver(o, this.selector, this));
  3784. };
  3785. inherits(InnerObserver, AbstractObserver);
  3786. function InnerObserver(o, selector, source) {
  3787. this.o = o;
  3788. this.selector = selector;
  3789. this.source = source;
  3790. this.i = 0;
  3791. AbstractObserver.call(this);
  3792. }
  3793. InnerObserver.prototype.next = function(x) {
  3794. var result = tryCatch(this.selector)(x, this.i++, this.source);
  3795. if (result === errorObj) { return this.o.onError(result.e); }
  3796. this.o.onNext(result);
  3797. };
  3798. InnerObserver.prototype.error = function (e) {
  3799. this.o.onError(e);
  3800. };
  3801. InnerObserver.prototype.completed = function () {
  3802. this.o.onCompleted();
  3803. };
  3804. return MapObservable;
  3805. }(ObservableBase));
  3806. /**
  3807. * Projects each element of an observable sequence into a new form by incorporating the element's index.
  3808. * @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.
  3809. * @param {Any} [thisArg] Object to use as this when executing callback.
  3810. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
  3811. */
  3812. observableProto.map = observableProto.select = function (selector, thisArg) {
  3813. var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
  3814. return this instanceof MapObservable ?
  3815. this.internalMap(selectorFn, thisArg) :
  3816. new MapObservable(this, selectorFn, thisArg);
  3817. };
  3818. function plucker(args, len) {
  3819. return function mapper(x) {
  3820. var currentProp = x;
  3821. for (var i = 0; i < len; i++) {
  3822. var p = currentProp[args[i]];
  3823. if (typeof p !== 'undefined') {
  3824. currentProp = p;
  3825. } else {
  3826. return undefined;
  3827. }
  3828. }
  3829. return currentProp;
  3830. };
  3831. }
  3832. /**
  3833. * Retrieves the value of a specified nested property from all elements in
  3834. * the Observable sequence.
  3835. * @param {Arguments} arguments The nested properties to pluck.
  3836. * @returns {Observable} Returns a new Observable sequence of property values.
  3837. */
  3838. observableProto.pluck = function () {
  3839. var len = arguments.length, args = new Array(len);
  3840. if (len === 0) { throw new Error('List of properties cannot be empty.'); }
  3841. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  3842. return this.map(plucker(args, len));
  3843. };
  3844. observableProto.flatMap = observableProto.selectMany = function(selector, resultSelector, thisArg) {
  3845. return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll();
  3846. };
  3847. Rx.Observable.prototype.flatMapLatest = function(selector, resultSelector, thisArg) {
  3848. return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest();
  3849. };
  3850. var SkipObservable = (function(__super__) {
  3851. inherits(SkipObservable, __super__);
  3852. function SkipObservable(source, count) {
  3853. this.source = source;
  3854. this._count = count;
  3855. __super__.call(this);
  3856. }
  3857. SkipObservable.prototype.subscribeCore = function (o) {
  3858. return this.source.subscribe(new SkipObserver(o, this._count));
  3859. };
  3860. function SkipObserver(o, c) {
  3861. this._o = o;
  3862. this._r = c;
  3863. AbstractObserver.call(this);
  3864. }
  3865. inherits(SkipObserver, AbstractObserver);
  3866. SkipObserver.prototype.next = function (x) {
  3867. if (this._r <= 0) {
  3868. this._o.onNext(x);
  3869. } else {
  3870. this._r--;
  3871. }
  3872. };
  3873. SkipObserver.prototype.error = function(e) { this._o.onError(e); };
  3874. SkipObserver.prototype.completed = function() { this._o.onCompleted(); };
  3875. return SkipObservable;
  3876. }(ObservableBase));
  3877. /**
  3878. * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
  3879. * @param {Number} count The number of elements to skip before returning the remaining elements.
  3880. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
  3881. */
  3882. observableProto.skip = function (count) {
  3883. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  3884. return new SkipObservable(this, count);
  3885. };
  3886. var SkipWhileObservable = (function (__super__) {
  3887. inherits(SkipWhileObservable, __super__);
  3888. function SkipWhileObservable(source, fn) {
  3889. this.source = source;
  3890. this._fn = fn;
  3891. __super__.call(this);
  3892. }
  3893. SkipWhileObservable.prototype.subscribeCore = function (o) {
  3894. return this.source.subscribe(new SkipWhileObserver(o, this));
  3895. };
  3896. return SkipWhileObservable;
  3897. }(ObservableBase));
  3898. var SkipWhileObserver = (function (__super__) {
  3899. inherits(SkipWhileObserver, __super__);
  3900. function SkipWhileObserver(o, p) {
  3901. this._o = o;
  3902. this._p = p;
  3903. this._i = 0;
  3904. this._r = false;
  3905. __super__.call(this);
  3906. }
  3907. SkipWhileObserver.prototype.next = function (x) {
  3908. if (!this._r) {
  3909. var res = tryCatch(this._p._fn)(x, this._i++, this._p);
  3910. if (res === errorObj) { return this._o.onError(res.e); }
  3911. this._r = !res;
  3912. }
  3913. this._r && this._o.onNext(x);
  3914. };
  3915. SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); };
  3916. SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
  3917. return SkipWhileObserver;
  3918. }(AbstractObserver));
  3919. /**
  3920. * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
  3921. * The element's index is used in the logic of the predicate function.
  3922. *
  3923. * var res = source.skipWhile(function (value) { return value < 10; });
  3924. * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
  3925. * @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.
  3926. * @param {Any} [thisArg] Object to use as this when executing callback.
  3927. * @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.
  3928. */
  3929. observableProto.skipWhile = function (predicate, thisArg) {
  3930. var fn = bindCallback(predicate, thisArg, 3);
  3931. return new SkipWhileObservable(this, fn);
  3932. };
  3933. var TakeObservable = (function(__super__) {
  3934. inherits(TakeObservable, __super__);
  3935. function TakeObservable(source, count) {
  3936. this.source = source;
  3937. this._count = count;
  3938. __super__.call(this);
  3939. }
  3940. TakeObservable.prototype.subscribeCore = function (o) {
  3941. return this.source.subscribe(new TakeObserver(o, this._count));
  3942. };
  3943. function TakeObserver(o, c) {
  3944. this._o = o;
  3945. this._c = c;
  3946. this._r = c;
  3947. AbstractObserver.call(this);
  3948. }
  3949. inherits(TakeObserver, AbstractObserver);
  3950. TakeObserver.prototype.next = function (x) {
  3951. if (this._r-- > 0) {
  3952. this._o.onNext(x);
  3953. this._r <= 0 && this._o.onCompleted();
  3954. }
  3955. };
  3956. TakeObserver.prototype.error = function (e) { this._o.onError(e); };
  3957. TakeObserver.prototype.completed = function () { this._o.onCompleted(); };
  3958. return TakeObservable;
  3959. }(ObservableBase));
  3960. /**
  3961. * 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).
  3962. * @param {Number} count The number of elements to return.
  3963. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
  3964. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
  3965. */
  3966. observableProto.take = function (count, scheduler) {
  3967. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  3968. if (count === 0) { return observableEmpty(scheduler); }
  3969. return new TakeObservable(this, count);
  3970. };
  3971. var TakeWhileObservable = (function (__super__) {
  3972. inherits(TakeWhileObservable, __super__);
  3973. function TakeWhileObservable(source, fn) {
  3974. this.source = source;
  3975. this._fn = fn;
  3976. __super__.call(this);
  3977. }
  3978. TakeWhileObservable.prototype.subscribeCore = function (o) {
  3979. return this.source.subscribe(new TakeWhileObserver(o, this));
  3980. };
  3981. return TakeWhileObservable;
  3982. }(ObservableBase));
  3983. var TakeWhileObserver = (function (__super__) {
  3984. inherits(TakeWhileObserver, __super__);
  3985. function TakeWhileObserver(o, p) {
  3986. this._o = o;
  3987. this._p = p;
  3988. this._i = 0;
  3989. this._r = true;
  3990. __super__.call(this);
  3991. }
  3992. TakeWhileObserver.prototype.next = function (x) {
  3993. if (this._r) {
  3994. this._r = tryCatch(this._p._fn)(x, this._i++, this._p);
  3995. if (this._r === errorObj) { return this._o.onError(this._r.e); }
  3996. }
  3997. if (this._r) {
  3998. this._o.onNext(x);
  3999. } else {
  4000. this._o.onCompleted();
  4001. }
  4002. };
  4003. TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); };
  4004. TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
  4005. return TakeWhileObserver;
  4006. }(AbstractObserver));
  4007. /**
  4008. * Returns elements from an observable sequence as long as a specified condition is true.
  4009. * The element's index is used in the logic of the predicate function.
  4010. * @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.
  4011. * @param {Any} [thisArg] Object to use as this when executing callback.
  4012. * @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.
  4013. */
  4014. observableProto.takeWhile = function (predicate, thisArg) {
  4015. var fn = bindCallback(predicate, thisArg, 3);
  4016. return new TakeWhileObservable(this, fn);
  4017. };
  4018. var FilterObservable = (function (__super__) {
  4019. inherits(FilterObservable, __super__);
  4020. function FilterObservable(source, predicate, thisArg) {
  4021. this.source = source;
  4022. this.predicate = bindCallback(predicate, thisArg, 3);
  4023. __super__.call(this);
  4024. }
  4025. FilterObservable.prototype.subscribeCore = function (o) {
  4026. return this.source.subscribe(new InnerObserver(o, this.predicate, this));
  4027. };
  4028. function innerPredicate(predicate, self) {
  4029. return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
  4030. }
  4031. FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
  4032. return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
  4033. };
  4034. inherits(InnerObserver, AbstractObserver);
  4035. function InnerObserver(o, predicate, source) {
  4036. this.o = o;
  4037. this.predicate = predicate;
  4038. this.source = source;
  4039. this.i = 0;
  4040. AbstractObserver.call(this);
  4041. }
  4042. InnerObserver.prototype.next = function(x) {
  4043. var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
  4044. if (shouldYield === errorObj) {
  4045. return this.o.onError(shouldYield.e);
  4046. }
  4047. shouldYield && this.o.onNext(x);
  4048. };
  4049. InnerObserver.prototype.error = function (e) {
  4050. this.o.onError(e);
  4051. };
  4052. InnerObserver.prototype.completed = function () {
  4053. this.o.onCompleted();
  4054. };
  4055. return FilterObservable;
  4056. }(ObservableBase));
  4057. /**
  4058. * Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
  4059. * @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.
  4060. * @param {Any} [thisArg] Object to use as this when executing callback.
  4061. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
  4062. */
  4063. observableProto.filter = observableProto.where = function (predicate, thisArg) {
  4064. return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
  4065. new FilterObservable(this, predicate, thisArg);
  4066. };
  4067. function createCbObservable(fn, ctx, selector, args) {
  4068. var o = new AsyncSubject();
  4069. args.push(createCbHandler(o, ctx, selector));
  4070. fn.apply(ctx, args);
  4071. return o.asObservable();
  4072. }
  4073. function createCbHandler(o, ctx, selector) {
  4074. return function handler () {
  4075. var len = arguments.length, results = new Array(len);
  4076. for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
  4077. if (isFunction(selector)) {
  4078. results = tryCatch(selector).apply(ctx, results);
  4079. if (results === errorObj) { return o.onError(results.e); }
  4080. o.onNext(results);
  4081. } else {
  4082. if (results.length <= 1) {
  4083. o.onNext(results[0]);
  4084. } else {
  4085. o.onNext(results);
  4086. }
  4087. }
  4088. o.onCompleted();
  4089. };
  4090. }
  4091. /**
  4092. * Converts a callback function to an observable sequence.
  4093. *
  4094. * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence.
  4095. * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
  4096. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
  4097. * @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.
  4098. */
  4099. Observable.fromCallback = function (fn, ctx, selector) {
  4100. return function () {
  4101. typeof ctx === 'undefined' && (ctx = this);
  4102. var len = arguments.length, args = new Array(len)
  4103. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  4104. return createCbObservable(fn, ctx, selector, args);
  4105. };
  4106. };
  4107. function createNodeObservable(fn, ctx, selector, args) {
  4108. var o = new AsyncSubject();
  4109. args.push(createNodeHandler(o, ctx, selector));
  4110. fn.apply(ctx, args);
  4111. return o.asObservable();
  4112. }
  4113. function createNodeHandler(o, ctx, selector) {
  4114. return function handler () {
  4115. var err = arguments[0];
  4116. if (err) { return o.onError(err); }
  4117. var len = arguments.length, results = [];
  4118. for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
  4119. if (isFunction(selector)) {
  4120. var results = tryCatch(selector).apply(ctx, results);
  4121. if (results === errorObj) { return o.onError(results.e); }
  4122. o.onNext(results);
  4123. } else {
  4124. if (results.length <= 1) {
  4125. o.onNext(results[0]);
  4126. } else {
  4127. o.onNext(results);
  4128. }
  4129. }
  4130. o.onCompleted();
  4131. };
  4132. }
  4133. /**
  4134. * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
  4135. * @param {Function} fn The function to call
  4136. * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
  4137. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
  4138. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
  4139. */
  4140. Observable.fromNodeCallback = function (fn, ctx, selector) {
  4141. return function () {
  4142. typeof ctx === 'undefined' && (ctx = this);
  4143. var len = arguments.length, args = new Array(len);
  4144. for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
  4145. return createNodeObservable(fn, ctx, selector, args);
  4146. };
  4147. };
  4148. function isNodeList(el) {
  4149. if (root.StaticNodeList) {
  4150. // IE8 Specific
  4151. // instanceof is slower than Object#toString, but Object#toString will not work as intended in IE8
  4152. return el instanceof root.StaticNodeList || el instanceof root.NodeList;
  4153. } else {
  4154. return Object.prototype.toString.call(el) === '[object NodeList]';
  4155. }
  4156. }
  4157. function ListenDisposable(e, n, fn) {
  4158. this._e = e;
  4159. this._n = n;
  4160. this._fn = fn;
  4161. this._e.addEventListener(this._n, this._fn, false);
  4162. this.isDisposed = false;
  4163. }
  4164. ListenDisposable.prototype.dispose = function () {
  4165. if (!this.isDisposed) {
  4166. this._e.removeEventListener(this._n, this._fn, false);
  4167. this.isDisposed = true;
  4168. }
  4169. };
  4170. function createEventListener (el, eventName, handler) {
  4171. var disposables = new CompositeDisposable();
  4172. // Asume NodeList or HTMLCollection
  4173. var elemToString = Object.prototype.toString.call(el);
  4174. if (isNodeList(el) || elemToString === '[object HTMLCollection]') {
  4175. for (var i = 0, len = el.length; i < len; i++) {
  4176. disposables.add(createEventListener(el.item(i), eventName, handler));
  4177. }
  4178. } else if (el) {
  4179. disposables.add(new ListenDisposable(el, eventName, handler));
  4180. }
  4181. return disposables;
  4182. }
  4183. /**
  4184. * Configuration option to determine whether to use native events only
  4185. */
  4186. Rx.config.useNativeEvents = false;
  4187. var EventObservable = (function(__super__) {
  4188. inherits(EventObservable, __super__);
  4189. function EventObservable(el, name, fn) {
  4190. this._el = el;
  4191. this._n = name;
  4192. this._fn = fn;
  4193. __super__.call(this);
  4194. }
  4195. function createHandler(o, fn) {
  4196. return function handler () {
  4197. var results = arguments[0];
  4198. if (isFunction(fn)) {
  4199. results = tryCatch(fn).apply(null, arguments);
  4200. if (results === errorObj) { return o.onError(results.e); }
  4201. }
  4202. o.onNext(results);
  4203. };
  4204. }
  4205. EventObservable.prototype.subscribeCore = function (o) {
  4206. return createEventListener(
  4207. this._el,
  4208. this._n,
  4209. createHandler(o, this._fn));
  4210. };
  4211. return EventObservable;
  4212. }(ObservableBase));
  4213. /**
  4214. * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
  4215. * @param {Object} element The DOMElement or NodeList to attach a listener.
  4216. * @param {String} eventName The event name to attach the observable sequence.
  4217. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
  4218. * @returns {Observable} An observable sequence of events from the specified element and the specified event.
  4219. */
  4220. Observable.fromEvent = function (element, eventName, selector) {
  4221. // Node.js specific
  4222. if (element.addListener) {
  4223. return fromEventPattern(
  4224. function (h) { element.addListener(eventName, h); },
  4225. function (h) { element.removeListener(eventName, h); },
  4226. selector);
  4227. }
  4228. // Use only if non-native events are allowed
  4229. if (!Rx.config.useNativeEvents) {
  4230. // Handles jq, Angular.js, Zepto, Marionette, Ember.js
  4231. if (typeof element.on === 'function' && typeof element.off === 'function') {
  4232. return fromEventPattern(
  4233. function (h) { element.on(eventName, h); },
  4234. function (h) { element.off(eventName, h); },
  4235. selector);
  4236. }
  4237. }
  4238. return new EventObservable(element, eventName, selector).publish().refCount();
  4239. };
  4240. var EventPatternObservable = (function(__super__) {
  4241. inherits(EventPatternObservable, __super__);
  4242. function EventPatternObservable(add, del, fn) {
  4243. this._add = add;
  4244. this._del = del;
  4245. this._fn = fn;
  4246. __super__.call(this);
  4247. }
  4248. function createHandler(o, fn) {
  4249. return function handler () {
  4250. var results = arguments[0];
  4251. if (isFunction(fn)) {
  4252. results = tryCatch(fn).apply(null, arguments);
  4253. if (results === errorObj) { return o.onError(results.e); }
  4254. }
  4255. o.onNext(results);
  4256. };
  4257. }
  4258. EventPatternObservable.prototype.subscribeCore = function (o) {
  4259. var fn = createHandler(o, this._fn);
  4260. var returnValue = this._add(fn);
  4261. return new EventPatternDisposable(this._del, fn, returnValue);
  4262. };
  4263. function EventPatternDisposable(del, fn, ret) {
  4264. this._del = del;
  4265. this._fn = fn;
  4266. this._ret = ret;
  4267. this.isDisposed = false;
  4268. }
  4269. EventPatternDisposable.prototype.dispose = function () {
  4270. if(!this.isDisposed) {
  4271. isFunction(this._del) && this._del(this._fn, this._ret);
  4272. this.isDisposed = true;
  4273. }
  4274. };
  4275. return EventPatternObservable;
  4276. }(ObservableBase));
  4277. /**
  4278. * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
  4279. * @param {Function} addHandler The function to add a handler to the emitter.
  4280. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
  4281. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
  4282. * @returns {Observable} An observable sequence which wraps an event from an event emitter
  4283. */
  4284. var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
  4285. return new EventPatternObservable(addHandler, removeHandler, selector).publish().refCount();
  4286. };
  4287. var FromPromiseObservable = (function(__super__) {
  4288. inherits(FromPromiseObservable, __super__);
  4289. function FromPromiseObservable(p, s) {
  4290. this._p = p;
  4291. this._s = s;
  4292. __super__.call(this);
  4293. }
  4294. function scheduleNext(s, state) {
  4295. var o = state[0], data = state[1];
  4296. o.onNext(data);
  4297. o.onCompleted();
  4298. }
  4299. function scheduleError(s, state) {
  4300. var o = state[0], err = state[1];
  4301. o.onError(err);
  4302. }
  4303. FromPromiseObservable.prototype.subscribeCore = function(o) {
  4304. var sad = new SingleAssignmentDisposable(), self = this;
  4305. this._p
  4306. .then(function (data) {
  4307. sad.setDisposable(self._s.schedule([o, data], scheduleNext));
  4308. }, function (err) {
  4309. sad.setDisposable(self._s.schedule([o, err], scheduleError));
  4310. });
  4311. return sad;
  4312. };
  4313. return FromPromiseObservable;
  4314. }(ObservableBase));
  4315. /**
  4316. * Converts a Promise to an Observable sequence
  4317. * @param {Promise} An ES6 Compliant promise.
  4318. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
  4319. */
  4320. var observableFromPromise = Observable.fromPromise = function (promise, scheduler) {
  4321. scheduler || (scheduler = defaultScheduler);
  4322. return new FromPromiseObservable(promise, scheduler);
  4323. };
  4324. /*
  4325. * Converts an existing observable sequence to an ES6 Compatible Promise
  4326. * @example
  4327. * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
  4328. *
  4329. * // With config
  4330. * Rx.config.Promise = RSVP.Promise;
  4331. * var promise = Rx.Observable.return(42).toPromise();
  4332. * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
  4333. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
  4334. */
  4335. observableProto.toPromise = function (promiseCtor) {
  4336. promiseCtor || (promiseCtor = Rx.config.Promise);
  4337. if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
  4338. var source = this;
  4339. return new promiseCtor(function (resolve, reject) {
  4340. // No cancellation can be done
  4341. var value;
  4342. source.subscribe(function (v) {
  4343. value = v;
  4344. }, reject, function () {
  4345. resolve(value);
  4346. });
  4347. });
  4348. };
  4349. /**
  4350. * Invokes the asynchronous function, surfacing the result through an observable sequence.
  4351. * @param {Function} functionAsync Asynchronous function which returns a Promise to run.
  4352. * @returns {Observable} An observable sequence exposing the function's result value, or an exception.
  4353. */
  4354. Observable.startAsync = function (functionAsync) {
  4355. var promise = tryCatch(functionAsync)();
  4356. if (promise === errorObj) { return observableThrow(promise.e); }
  4357. return observableFromPromise(promise);
  4358. };
  4359. var MulticastObservable = (function (__super__) {
  4360. inherits(MulticastObservable, __super__);
  4361. function MulticastObservable(source, fn1, fn2) {
  4362. this.source = source;
  4363. this._fn1 = fn1;
  4364. this._fn2 = fn2;
  4365. __super__.call(this);
  4366. }
  4367. MulticastObservable.prototype.subscribeCore = function (o) {
  4368. var connectable = this.source.multicast(this._fn1());
  4369. return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());
  4370. };
  4371. return MulticastObservable;
  4372. }(ObservableBase));
  4373. /**
  4374. * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
  4375. * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
  4376. * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
  4377. *
  4378. * @example
  4379. * 1 - res = source.multicast(observable);
  4380. * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
  4381. *
  4382. * @param {Function|Subject} subjectOrSubjectSelector
  4383. * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
  4384. * Or:
  4385. * Subject to push source elements into.
  4386. *
  4387. * @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.
  4388. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  4389. */
  4390. observableProto.multicast = function (subjectOrSubjectSelector, selector) {
  4391. return isFunction(subjectOrSubjectSelector) ?
  4392. new MulticastObservable(this, subjectOrSubjectSelector, selector) :
  4393. new ConnectableObservable(this, subjectOrSubjectSelector);
  4394. };
  4395. /**
  4396. * 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.
  4397. * This operator is a specialization of Multicast using a regular Subject.
  4398. *
  4399. * @example
  4400. * var resres = source.publish();
  4401. * var res = source.publish(function (x) { return x; });
  4402. *
  4403. * @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.
  4404. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  4405. */
  4406. observableProto.publish = function (selector) {
  4407. return selector && isFunction(selector) ?
  4408. this.multicast(function () { return new Subject(); }, selector) :
  4409. this.multicast(new Subject());
  4410. };
  4411. /**
  4412. * Returns an observable sequence that shares a single subscription to the underlying sequence.
  4413. * 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.
  4414. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  4415. */
  4416. observableProto.share = function () {
  4417. return this.publish().refCount();
  4418. };
  4419. /**
  4420. * 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.
  4421. * This operator is a specialization of Multicast using a AsyncSubject.
  4422. *
  4423. * @example
  4424. * var res = source.publishLast();
  4425. * var res = source.publishLast(function (x) { return x; });
  4426. *
  4427. * @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.
  4428. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  4429. */
  4430. observableProto.publishLast = function (selector) {
  4431. return selector && isFunction(selector) ?
  4432. this.multicast(function () { return new AsyncSubject(); }, selector) :
  4433. this.multicast(new AsyncSubject());
  4434. };
  4435. /**
  4436. * 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.
  4437. * This operator is a specialization of Multicast using a BehaviorSubject.
  4438. *
  4439. * @example
  4440. * var res = source.publishValue(42);
  4441. * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
  4442. *
  4443. * @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.
  4444. * @param {Mixed} initialValue Initial value received by observers upon subscription.
  4445. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  4446. */
  4447. observableProto.publishValue = function (initialValueOrSelector, initialValue) {
  4448. return arguments.length === 2 ?
  4449. this.multicast(function () {
  4450. return new BehaviorSubject(initialValue);
  4451. }, initialValueOrSelector) :
  4452. this.multicast(new BehaviorSubject(initialValueOrSelector));
  4453. };
  4454. /**
  4455. * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
  4456. * 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.
  4457. * @param {Mixed} initialValue Initial value received by observers upon subscription.
  4458. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  4459. */
  4460. observableProto.shareValue = function (initialValue) {
  4461. return this.publishValue(initialValue).refCount();
  4462. };
  4463. /**
  4464. * 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.
  4465. * This operator is a specialization of Multicast using a ReplaySubject.
  4466. *
  4467. * @example
  4468. * var res = source.replay(null, 3);
  4469. * var res = source.replay(null, 3, 500);
  4470. * var res = source.replay(null, 3, 500, scheduler);
  4471. * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
  4472. *
  4473. * @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.
  4474. * @param bufferSize [Optional] Maximum element count of the replay buffer.
  4475. * @param windowSize [Optional] Maximum time length of the replay buffer.
  4476. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
  4477. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  4478. */
  4479. observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
  4480. return selector && isFunction(selector) ?
  4481. this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
  4482. this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
  4483. };
  4484. /**
  4485. * 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.
  4486. * 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.
  4487. *
  4488. * @example
  4489. * var res = source.shareReplay(3);
  4490. * var res = source.shareReplay(3, 500);
  4491. * var res = source.shareReplay(3, 500, scheduler);
  4492. *
  4493. * @param bufferSize [Optional] Maximum element count of the replay buffer.
  4494. * @param window [Optional] Maximum time length of the replay buffer.
  4495. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
  4496. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  4497. */
  4498. observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
  4499. return this.replay(null, bufferSize, windowSize, scheduler).refCount();
  4500. };
  4501. var RefCountObservable = (function (__super__) {
  4502. inherits(RefCountObservable, __super__);
  4503. function RefCountObservable(source) {
  4504. this.source = source;
  4505. this._count = 0;
  4506. this._connectableSubscription = null;
  4507. __super__.call(this);
  4508. }
  4509. RefCountObservable.prototype.subscribeCore = function (o) {
  4510. var subscription = this.source.subscribe(o);
  4511. ++this._count === 1 && (this._connectableSubscription = this.source.connect());
  4512. return new RefCountDisposable(this, subscription);
  4513. };
  4514. function RefCountDisposable(p, s) {
  4515. this._p = p;
  4516. this._s = s;
  4517. this.isDisposed = false;
  4518. }
  4519. RefCountDisposable.prototype.dispose = function () {
  4520. if (!this.isDisposed) {
  4521. this.isDisposed = true;
  4522. this._s.dispose();
  4523. --this._p._count === 0 && this._p._connectableSubscription.dispose();
  4524. }
  4525. };
  4526. return RefCountObservable;
  4527. }(ObservableBase));
  4528. var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
  4529. inherits(ConnectableObservable, __super__);
  4530. function ConnectableObservable(source, subject) {
  4531. this.source = source;
  4532. this._connection = null;
  4533. this._source = source.asObservable();
  4534. this._subject = subject;
  4535. __super__.call(this);
  4536. }
  4537. function ConnectDisposable(parent, subscription) {
  4538. this._p = parent;
  4539. this._s = subscription;
  4540. }
  4541. ConnectDisposable.prototype.dispose = function () {
  4542. if (this._s) {
  4543. this._s.dispose();
  4544. this._s = null;
  4545. this._p._connection = null;
  4546. }
  4547. };
  4548. ConnectableObservable.prototype.connect = function () {
  4549. if (!this._connection) {
  4550. var subscription = this._source.subscribe(this._subject);
  4551. this._connection = new ConnectDisposable(this, subscription);
  4552. }
  4553. return this._connection;
  4554. };
  4555. ConnectableObservable.prototype._subscribe = function (o) {
  4556. return this._subject.subscribe(o);
  4557. };
  4558. ConnectableObservable.prototype.refCount = function () {
  4559. return new RefCountObservable(this);
  4560. };
  4561. return ConnectableObservable;
  4562. }(Observable));
  4563. var TimerObservable = (function(__super__) {
  4564. inherits(TimerObservable, __super__);
  4565. function TimerObservable(dt, s) {
  4566. this._dt = dt;
  4567. this._s = s;
  4568. __super__.call(this);
  4569. }
  4570. TimerObservable.prototype.subscribeCore = function (o) {
  4571. return this._s.scheduleFuture(o, this._dt, scheduleMethod);
  4572. };
  4573. function scheduleMethod(s, o) {
  4574. o.onNext(0);
  4575. o.onCompleted();
  4576. }
  4577. return TimerObservable;
  4578. }(ObservableBase));
  4579. function _observableTimer(dueTime, scheduler) {
  4580. return new TimerObservable(dueTime, scheduler);
  4581. }
  4582. function observableTimerDateAndPeriod(dueTime, period, scheduler) {
  4583. return new AnonymousObservable(function (observer) {
  4584. var d = dueTime, p = normalizeTime(period);
  4585. return scheduler.scheduleRecursiveFuture(0, d, function (count, self) {
  4586. if (p > 0) {
  4587. var now = scheduler.now();
  4588. d = new Date(d.getTime() + p);
  4589. d.getTime() <= now && (d = new Date(now + p));
  4590. }
  4591. observer.onNext(count);
  4592. self(count + 1, new Date(d));
  4593. });
  4594. });
  4595. }
  4596. function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
  4597. return dueTime === period ?
  4598. new AnonymousObservable(function (observer) {
  4599. return scheduler.schedulePeriodic(0, period, function (count) {
  4600. observer.onNext(count);
  4601. return count + 1;
  4602. });
  4603. }) :
  4604. observableDefer(function () {
  4605. return observableTimerDateAndPeriod(new Date(scheduler.now() + dueTime), period, scheduler);
  4606. });
  4607. }
  4608. /**
  4609. * Returns an observable sequence that produces a value after each period.
  4610. *
  4611. * @example
  4612. * 1 - res = Rx.Observable.interval(1000);
  4613. * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
  4614. *
  4615. * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
  4616. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
  4617. * @returns {Observable} An observable sequence that produces a value after each period.
  4618. */
  4619. var observableinterval = Observable.interval = function (period, scheduler) {
  4620. return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : defaultScheduler);
  4621. };
  4622. /**
  4623. * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
  4624. * @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.
  4625. * @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.
  4626. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
  4627. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
  4628. */
  4629. var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
  4630. var period;
  4631. isScheduler(scheduler) || (scheduler = defaultScheduler);
  4632. if (periodOrScheduler != null && typeof periodOrScheduler === 'number') {
  4633. period = periodOrScheduler;
  4634. } else if (isScheduler(periodOrScheduler)) {
  4635. scheduler = periodOrScheduler;
  4636. }
  4637. if ((dueTime instanceof Date || typeof dueTime === 'number') && period === undefined) {
  4638. return _observableTimer(dueTime, scheduler);
  4639. }
  4640. if (dueTime instanceof Date && period !== undefined) {
  4641. return observableTimerDateAndPeriod(dueTime, periodOrScheduler, scheduler);
  4642. }
  4643. return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
  4644. };
  4645. function observableDelayRelative(source, dueTime, scheduler) {
  4646. return new AnonymousObservable(function (o) {
  4647. var active = false,
  4648. cancelable = new SerialDisposable(),
  4649. exception = null,
  4650. q = [],
  4651. running = false,
  4652. subscription;
  4653. subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
  4654. var d, shouldRun;
  4655. if (notification.value.kind === 'E') {
  4656. q = [];
  4657. q.push(notification);
  4658. exception = notification.value.error;
  4659. shouldRun = !running;
  4660. } else {
  4661. q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
  4662. shouldRun = !active;
  4663. active = true;
  4664. }
  4665. if (shouldRun) {
  4666. if (exception !== null) {
  4667. o.onError(exception);
  4668. } else {
  4669. d = new SingleAssignmentDisposable();
  4670. cancelable.setDisposable(d);
  4671. d.setDisposable(scheduler.scheduleRecursiveFuture(null, dueTime, function (_, self) {
  4672. var e, recurseDueTime, result, shouldRecurse;
  4673. if (exception !== null) {
  4674. return;
  4675. }
  4676. running = true;
  4677. do {
  4678. result = null;
  4679. if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
  4680. result = q.shift().value;
  4681. }
  4682. if (result !== null) {
  4683. result.accept(o);
  4684. }
  4685. } while (result !== null);
  4686. shouldRecurse = false;
  4687. recurseDueTime = 0;
  4688. if (q.length > 0) {
  4689. shouldRecurse = true;
  4690. recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
  4691. } else {
  4692. active = false;
  4693. }
  4694. e = exception;
  4695. running = false;
  4696. if (e !== null) {
  4697. o.onError(e);
  4698. } else if (shouldRecurse) {
  4699. self(null, recurseDueTime);
  4700. }
  4701. }));
  4702. }
  4703. }
  4704. });
  4705. return new BinaryDisposable(subscription, cancelable);
  4706. }, source);
  4707. }
  4708. function observableDelayAbsolute(source, dueTime, scheduler) {
  4709. return observableDefer(function () {
  4710. return observableDelayRelative(source, dueTime - scheduler.now(), scheduler);
  4711. });
  4712. }
  4713. function delayWithSelector(source, subscriptionDelay, delayDurationSelector) {
  4714. var subDelay, selector;
  4715. if (isFunction(subscriptionDelay)) {
  4716. selector = subscriptionDelay;
  4717. } else {
  4718. subDelay = subscriptionDelay;
  4719. selector = delayDurationSelector;
  4720. }
  4721. return new AnonymousObservable(function (o) {
  4722. var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable();
  4723. function start() {
  4724. subscription.setDisposable(source.subscribe(
  4725. function (x) {
  4726. var delay = tryCatch(selector)(x);
  4727. if (delay === errorObj) { return o.onError(delay.e); }
  4728. var d = new SingleAssignmentDisposable();
  4729. delays.add(d);
  4730. d.setDisposable(delay.subscribe(
  4731. function () {
  4732. o.onNext(x);
  4733. delays.remove(d);
  4734. done();
  4735. },
  4736. function (e) { o.onError(e); },
  4737. function () {
  4738. o.onNext(x);
  4739. delays.remove(d);
  4740. done();
  4741. }
  4742. ));
  4743. },
  4744. function (e) { o.onError(e); },
  4745. function () {
  4746. atEnd = true;
  4747. subscription.dispose();
  4748. done();
  4749. }
  4750. ));
  4751. }
  4752. function done () {
  4753. atEnd && delays.length === 0 && o.onCompleted();
  4754. }
  4755. if (!subDelay) {
  4756. start();
  4757. } else {
  4758. subscription.setDisposable(subDelay.subscribe(start, function (e) { o.onError(e); }, start));
  4759. }
  4760. return new BinaryDisposable(subscription, delays);
  4761. }, source);
  4762. }
  4763. /**
  4764. * Time shifts the observable sequence by dueTime.
  4765. * The relative time intervals between the values are preserved.
  4766. *
  4767. * @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.
  4768. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
  4769. * @returns {Observable} Time-shifted sequence.
  4770. */
  4771. observableProto.delay = function () {
  4772. var firstArg = arguments[0];
  4773. if (typeof firstArg === 'number' || firstArg instanceof Date) {
  4774. var dueTime = firstArg, scheduler = arguments[1];
  4775. isScheduler(scheduler) || (scheduler = defaultScheduler);
  4776. return dueTime instanceof Date ?
  4777. observableDelayAbsolute(this, dueTime, scheduler) :
  4778. observableDelayRelative(this, dueTime, scheduler);
  4779. } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
  4780. return delayWithSelector(this, firstArg, arguments[1]);
  4781. } else {
  4782. throw new Error('Invalid arguments');
  4783. }
  4784. };
  4785. var DebounceObservable = (function (__super__) {
  4786. inherits(DebounceObservable, __super__);
  4787. function DebounceObservable(source, dt, s) {
  4788. isScheduler(s) || (s = defaultScheduler);
  4789. this.source = source;
  4790. this._dt = dt;
  4791. this._s = s;
  4792. __super__.call(this);
  4793. }
  4794. DebounceObservable.prototype.subscribeCore = function (o) {
  4795. var cancelable = new SerialDisposable();
  4796. return new BinaryDisposable(
  4797. this.source.subscribe(new DebounceObserver(o, this._dt, this._s, cancelable)),
  4798. cancelable);
  4799. };
  4800. return DebounceObservable;
  4801. }(ObservableBase));
  4802. var DebounceObserver = (function (__super__) {
  4803. inherits(DebounceObserver, __super__);
  4804. function DebounceObserver(observer, dueTime, scheduler, cancelable) {
  4805. this._o = observer;
  4806. this._d = dueTime;
  4807. this._scheduler = scheduler;
  4808. this._c = cancelable;
  4809. this._v = null;
  4810. this._hv = false;
  4811. this._id = 0;
  4812. __super__.call(this);
  4813. }
  4814. function scheduleFuture(s, state) {
  4815. state.self._hv && state.self._id === state.currentId && state.self._o.onNext(state.x);
  4816. state.self._hv = false;
  4817. }
  4818. DebounceObserver.prototype.next = function (x) {
  4819. this._hv = true;
  4820. this._v = x;
  4821. var currentId = ++this._id, d = new SingleAssignmentDisposable();
  4822. this._c.setDisposable(d);
  4823. d.setDisposable(this._scheduler.scheduleFuture(this, this._d, function (_, self) {
  4824. self._hv && self._id === currentId && self._o.onNext(x);
  4825. self._hv = false;
  4826. }));
  4827. };
  4828. DebounceObserver.prototype.error = function (e) {
  4829. this._c.dispose();
  4830. this._o.onError(e);
  4831. this._hv = false;
  4832. this._id++;
  4833. };
  4834. DebounceObserver.prototype.completed = function () {
  4835. this._c.dispose();
  4836. this._hv && this._o.onNext(this._v);
  4837. this._o.onCompleted();
  4838. this._hv = false;
  4839. this._id++;
  4840. };
  4841. return DebounceObserver;
  4842. }(AbstractObserver));
  4843. function debounceWithSelector(source, durationSelector) {
  4844. return new AnonymousObservable(function (o) {
  4845. var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
  4846. var subscription = source.subscribe(
  4847. function (x) {
  4848. var throttle = tryCatch(durationSelector)(x);
  4849. if (throttle === errorObj) { return o.onError(throttle.e); }
  4850. isPromise(throttle) && (throttle = observableFromPromise(throttle));
  4851. hasValue = true;
  4852. value = x;
  4853. id++;
  4854. var currentid = id, d = new SingleAssignmentDisposable();
  4855. cancelable.setDisposable(d);
  4856. d.setDisposable(throttle.subscribe(
  4857. function () {
  4858. hasValue && id === currentid && o.onNext(value);
  4859. hasValue = false;
  4860. d.dispose();
  4861. },
  4862. function (e) { o.onError(e); },
  4863. function () {
  4864. hasValue && id === currentid && o.onNext(value);
  4865. hasValue = false;
  4866. d.dispose();
  4867. }
  4868. ));
  4869. },
  4870. function (e) {
  4871. cancelable.dispose();
  4872. o.onError(e);
  4873. hasValue = false;
  4874. id++;
  4875. },
  4876. function () {
  4877. cancelable.dispose();
  4878. hasValue && o.onNext(value);
  4879. o.onCompleted();
  4880. hasValue = false;
  4881. id++;
  4882. }
  4883. );
  4884. return new BinaryDisposable(subscription, cancelable);
  4885. }, source);
  4886. }
  4887. observableProto.debounce = function () {
  4888. if (isFunction (arguments[0])) {
  4889. return debounceWithSelector(this, arguments[0]);
  4890. } else if (typeof arguments[0] === 'number') {
  4891. return new DebounceObservable(this, arguments[0], arguments[1]);
  4892. } else {
  4893. throw new Error('Invalid arguments');
  4894. }
  4895. };
  4896. var TimestampObservable = (function (__super__) {
  4897. inherits(TimestampObservable, __super__);
  4898. function TimestampObservable(source, s) {
  4899. this.source = source;
  4900. this._s = s;
  4901. __super__.call(this);
  4902. }
  4903. TimestampObservable.prototype.subscribeCore = function (o) {
  4904. return this.source.subscribe(new TimestampObserver(o, this._s));
  4905. };
  4906. return TimestampObservable;
  4907. }(ObservableBase));
  4908. var TimestampObserver = (function (__super__) {
  4909. inherits(TimestampObserver, __super__);
  4910. function TimestampObserver(o, s) {
  4911. this._o = o;
  4912. this._s = s;
  4913. __super__.call(this);
  4914. }
  4915. TimestampObserver.prototype.next = function (x) {
  4916. this._o.onNext({ value: x, timestamp: this._s.now() });
  4917. };
  4918. TimestampObserver.prototype.error = function (e) {
  4919. this._o.onError(e);
  4920. };
  4921. TimestampObserver.prototype.completed = function () {
  4922. this._o.onCompleted();
  4923. };
  4924. return TimestampObserver;
  4925. }(AbstractObserver));
  4926. /**
  4927. * Records the timestamp for each value in an observable sequence.
  4928. *
  4929. * @example
  4930. * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
  4931. * 2 - res = source.timestamp(Rx.Scheduler.default);
  4932. *
  4933. * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used.
  4934. * @returns {Observable} An observable sequence with timestamp information on values.
  4935. */
  4936. observableProto.timestamp = function (scheduler) {
  4937. isScheduler(scheduler) || (scheduler = defaultScheduler);
  4938. return new TimestampObservable(this, scheduler);
  4939. };
  4940. var SampleObservable = (function(__super__) {
  4941. inherits(SampleObservable, __super__);
  4942. function SampleObservable(source, sampler) {
  4943. this.source = source;
  4944. this._sampler = sampler;
  4945. __super__.call(this);
  4946. }
  4947. SampleObservable.prototype.subscribeCore = function (o) {
  4948. var state = {
  4949. o: o,
  4950. atEnd: false,
  4951. value: null,
  4952. hasValue: false,
  4953. sourceSubscription: new SingleAssignmentDisposable()
  4954. };
  4955. state.sourceSubscription.setDisposable(this.source.subscribe(new SampleSourceObserver(state)));
  4956. return new BinaryDisposable(
  4957. state.sourceSubscription,
  4958. this._sampler.subscribe(new SamplerObserver(state))
  4959. );
  4960. };
  4961. return SampleObservable;
  4962. }(ObservableBase));
  4963. var SamplerObserver = (function(__super__) {
  4964. inherits(SamplerObserver, __super__);
  4965. function SamplerObserver(s) {
  4966. this._s = s;
  4967. __super__.call(this);
  4968. }
  4969. SamplerObserver.prototype._handleMessage = function () {
  4970. if (this._s.hasValue) {
  4971. this._s.hasValue = false;
  4972. this._s.o.onNext(this._s.value);
  4973. }
  4974. this._s.atEnd && this._s.o.onCompleted();
  4975. };
  4976. SamplerObserver.prototype.next = function () { this._handleMessage(); };
  4977. SamplerObserver.prototype.error = function (e) { this._s.onError(e); };
  4978. SamplerObserver.prototype.completed = function () { this._handleMessage(); };
  4979. return SamplerObserver;
  4980. }(AbstractObserver));
  4981. var SampleSourceObserver = (function(__super__) {
  4982. inherits(SampleSourceObserver, __super__);
  4983. function SampleSourceObserver(s) {
  4984. this._s = s;
  4985. __super__.call(this);
  4986. }
  4987. SampleSourceObserver.prototype.next = function (x) {
  4988. this._s.hasValue = true;
  4989. this._s.value = x;
  4990. };
  4991. SampleSourceObserver.prototype.error = function (e) { this._s.o.onError(e); };
  4992. SampleSourceObserver.prototype.completed = function () {
  4993. this._s.atEnd = true;
  4994. this._s.sourceSubscription.dispose();
  4995. };
  4996. return SampleSourceObserver;
  4997. }(AbstractObserver));
  4998. /**
  4999. * Samples the observable sequence at each interval.
  5000. *
  5001. * @example
  5002. * 1 - res = source.sample(sampleObservable); // Sampler tick sequence
  5003. * 2 - res = source.sample(5000); // 5 seconds
  5004. * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
  5005. *
  5006. * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
  5007. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
  5008. * @returns {Observable} Sampled observable sequence.
  5009. */
  5010. observableProto.sample = function (intervalOrSampler, scheduler) {
  5011. isScheduler(scheduler) || (scheduler = defaultScheduler);
  5012. return typeof intervalOrSampler === 'number' ?
  5013. new SampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
  5014. new SampleObservable(this, intervalOrSampler);
  5015. };
  5016. var TimeoutError = Rx.TimeoutError = function(message) {
  5017. this.message = message || 'Timeout has occurred';
  5018. this.name = 'TimeoutError';
  5019. Error.call(this);
  5020. };
  5021. TimeoutError.prototype = Object.create(Error.prototype);
  5022. function timeoutWithSelector(source, firstTimeout, timeoutDurationSelector, other) {
  5023. if (isFunction(firstTimeout)) {
  5024. other = timeoutDurationSelector;
  5025. timeoutDurationSelector = firstTimeout;
  5026. firstTimeout = observableNever();
  5027. }
  5028. Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
  5029. return new AnonymousObservable(function (o) {
  5030. var subscription = new SerialDisposable(),
  5031. timer = new SerialDisposable(),
  5032. original = new SingleAssignmentDisposable();
  5033. subscription.setDisposable(original);
  5034. var id = 0, switched = false;
  5035. function setTimer(timeout) {
  5036. var myId = id, d = new SingleAssignmentDisposable();
  5037. function timerWins() {
  5038. switched = (myId === id);
  5039. return switched;
  5040. }
  5041. timer.setDisposable(d);
  5042. d.setDisposable(timeout.subscribe(function () {
  5043. timerWins() && subscription.setDisposable(other.subscribe(o));
  5044. d.dispose();
  5045. }, function (e) {
  5046. timerWins() && o.onError(e);
  5047. }, function () {
  5048. timerWins() && subscription.setDisposable(other.subscribe(o));
  5049. }));
  5050. };
  5051. setTimer(firstTimeout);
  5052. function oWins() {
  5053. var res = !switched;
  5054. if (res) { id++; }
  5055. return res;
  5056. }
  5057. original.setDisposable(source.subscribe(function (x) {
  5058. if (oWins()) {
  5059. o.onNext(x);
  5060. var timeout = tryCatch(timeoutDurationSelector)(x);
  5061. if (timeout === errorObj) { return o.onError(timeout.e); }
  5062. setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
  5063. }
  5064. }, function (e) {
  5065. oWins() && o.onError(e);
  5066. }, function () {
  5067. oWins() && o.onCompleted();
  5068. }));
  5069. return new BinaryDisposable(subscription, timer);
  5070. }, source);
  5071. }
  5072. function timeout(source, dueTime, other, scheduler) {
  5073. if (isScheduler(other)) {
  5074. scheduler = other;
  5075. other = observableThrow(new TimeoutError());
  5076. }
  5077. if (other instanceof Error) { other = observableThrow(other); }
  5078. isScheduler(scheduler) || (scheduler = defaultScheduler);
  5079. Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
  5080. return new AnonymousObservable(function (o) {
  5081. var id = 0,
  5082. original = new SingleAssignmentDisposable(),
  5083. subscription = new SerialDisposable(),
  5084. switched = false,
  5085. timer = new SerialDisposable();
  5086. subscription.setDisposable(original);
  5087. function createTimer() {
  5088. var myId = id;
  5089. timer.setDisposable(scheduler.scheduleFuture(null, dueTime, function () {
  5090. switched = id === myId;
  5091. if (switched) {
  5092. isPromise(other) && (other = observableFromPromise(other));
  5093. subscription.setDisposable(other.subscribe(o));
  5094. }
  5095. }));
  5096. }
  5097. createTimer();
  5098. original.setDisposable(source.subscribe(function (x) {
  5099. if (!switched) {
  5100. id++;
  5101. o.onNext(x);
  5102. createTimer();
  5103. }
  5104. }, function (e) {
  5105. if (!switched) {
  5106. id++;
  5107. o.onError(e);
  5108. }
  5109. }, function () {
  5110. if (!switched) {
  5111. id++;
  5112. o.onCompleted();
  5113. }
  5114. }));
  5115. return new BinaryDisposable(subscription, timer);
  5116. }, source);
  5117. }
  5118. observableProto.timeout = function () {
  5119. var firstArg = arguments[0];
  5120. if (firstArg instanceof Date || typeof firstArg === 'number') {
  5121. return timeout(this, firstArg, arguments[1], arguments[2]);
  5122. } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
  5123. return timeoutWithSelector(this, firstArg, arguments[1], arguments[2]);
  5124. } else {
  5125. throw new Error('Invalid arguments');
  5126. }
  5127. };
  5128. /**
  5129. * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
  5130. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item
  5131. * @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.
  5132. * @returns {Observable} An Observable that performs the throttle operation.
  5133. */
  5134. observableProto.throttle = function (windowDuration, scheduler) {
  5135. isScheduler(scheduler) || (scheduler = defaultScheduler);
  5136. var duration = +windowDuration || 0;
  5137. if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
  5138. var source = this;
  5139. return new AnonymousObservable(function (o) {
  5140. var lastOnNext = 0;
  5141. return source.subscribe(
  5142. function (x) {
  5143. var now = scheduler.now();
  5144. if (lastOnNext === 0 || now - lastOnNext >= duration) {
  5145. lastOnNext = now;
  5146. o.onNext(x);
  5147. }
  5148. },function (e) { o.onError(e); }, function () { o.onCompleted(); }
  5149. );
  5150. }, source);
  5151. };
  5152. var PausableObservable = (function (__super__) {
  5153. inherits(PausableObservable, __super__);
  5154. function PausableObservable(source, pauser) {
  5155. this.source = source;
  5156. this.controller = new Subject();
  5157. if (pauser && pauser.subscribe) {
  5158. this.pauser = this.controller.merge(pauser);
  5159. } else {
  5160. this.pauser = this.controller;
  5161. }
  5162. __super__.call(this);
  5163. }
  5164. PausableObservable.prototype._subscribe = function (o) {
  5165. var conn = this.source.publish(),
  5166. subscription = conn.subscribe(o),
  5167. connection = disposableEmpty;
  5168. var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
  5169. if (b) {
  5170. connection = conn.connect();
  5171. } else {
  5172. connection.dispose();
  5173. connection = disposableEmpty;
  5174. }
  5175. });
  5176. return new NAryDisposable([subscription, connection, pausable]);
  5177. };
  5178. PausableObservable.prototype.pause = function () {
  5179. this.controller.onNext(false);
  5180. };
  5181. PausableObservable.prototype.resume = function () {
  5182. this.controller.onNext(true);
  5183. };
  5184. return PausableObservable;
  5185. }(Observable));
  5186. /**
  5187. * Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
  5188. * @example
  5189. * var pauser = new Rx.Subject();
  5190. * var source = Rx.Observable.interval(100).pausable(pauser);
  5191. * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
  5192. * @returns {Observable} The observable sequence which is paused based upon the pauser.
  5193. */
  5194. observableProto.pausable = function (pauser) {
  5195. return new PausableObservable(this, pauser);
  5196. };
  5197. function combineLatestSource(source, subject, resultSelector) {
  5198. return new AnonymousObservable(function (o) {
  5199. var hasValue = [false, false],
  5200. hasValueAll = false,
  5201. isDone = false,
  5202. values = new Array(2),
  5203. err;
  5204. function next(x, i) {
  5205. values[i] = x;
  5206. hasValue[i] = true;
  5207. if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
  5208. if (err) { return o.onError(err); }
  5209. var res = tryCatch(resultSelector).apply(null, values);
  5210. if (res === errorObj) { return o.onError(res.e); }
  5211. o.onNext(res);
  5212. }
  5213. isDone && values[1] && o.onCompleted();
  5214. }
  5215. return new BinaryDisposable(
  5216. source.subscribe(
  5217. function (x) {
  5218. next(x, 0);
  5219. },
  5220. function (e) {
  5221. if (values[1]) {
  5222. o.onError(e);
  5223. } else {
  5224. err = e;
  5225. }
  5226. },
  5227. function () {
  5228. isDone = true;
  5229. values[1] && o.onCompleted();
  5230. }),
  5231. subject.subscribe(
  5232. function (x) {
  5233. next(x, 1);
  5234. },
  5235. function (e) { o.onError(e); },
  5236. function () {
  5237. isDone = true;
  5238. next(true, 1);
  5239. })
  5240. );
  5241. }, source);
  5242. }
  5243. var PausableBufferedObservable = (function (__super__) {
  5244. inherits(PausableBufferedObservable, __super__);
  5245. function PausableBufferedObservable(source, pauser) {
  5246. this.source = source;
  5247. this.controller = new Subject();
  5248. if (pauser && pauser.subscribe) {
  5249. this.pauser = this.controller.merge(pauser);
  5250. } else {
  5251. this.pauser = this.controller;
  5252. }
  5253. __super__.call(this);
  5254. }
  5255. PausableBufferedObservable.prototype._subscribe = function (o) {
  5256. var q = [], previousShouldFire;
  5257. function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } }
  5258. var subscription =
  5259. combineLatestSource(
  5260. this.source,
  5261. this.pauser.startWith(false).distinctUntilChanged(),
  5262. function (data, shouldFire) {
  5263. return { data: data, shouldFire: shouldFire };
  5264. })
  5265. .subscribe(
  5266. function (results) {
  5267. if (previousShouldFire !== undefined && results.shouldFire !== previousShouldFire) {
  5268. previousShouldFire = results.shouldFire;
  5269. // change in shouldFire
  5270. if (results.shouldFire) { drainQueue(); }
  5271. } else {
  5272. previousShouldFire = results.shouldFire;
  5273. // new data
  5274. if (results.shouldFire) {
  5275. o.onNext(results.data);
  5276. } else {
  5277. q.push(results.data);
  5278. }
  5279. }
  5280. },
  5281. function (err) {
  5282. drainQueue();
  5283. o.onError(err);
  5284. },
  5285. function () {
  5286. drainQueue();
  5287. o.onCompleted();
  5288. }
  5289. );
  5290. return subscription;
  5291. };
  5292. PausableBufferedObservable.prototype.pause = function () {
  5293. this.controller.onNext(false);
  5294. };
  5295. PausableBufferedObservable.prototype.resume = function () {
  5296. this.controller.onNext(true);
  5297. };
  5298. return PausableBufferedObservable;
  5299. }(Observable));
  5300. /**
  5301. * Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
  5302. * and yields the values that were buffered while paused.
  5303. * @example
  5304. * var pauser = new Rx.Subject();
  5305. * var source = Rx.Observable.interval(100).pausableBuffered(pauser);
  5306. * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
  5307. * @returns {Observable} The observable sequence which is paused based upon the pauser.
  5308. */
  5309. observableProto.pausableBuffered = function (pauser) {
  5310. return new PausableBufferedObservable(this, pauser);
  5311. };
  5312. var ControlledObservable = (function (__super__) {
  5313. inherits(ControlledObservable, __super__);
  5314. function ControlledObservable (source, enableQueue, scheduler) {
  5315. __super__.call(this);
  5316. this.subject = new ControlledSubject(enableQueue, scheduler);
  5317. this.source = source.multicast(this.subject).refCount();
  5318. }
  5319. ControlledObservable.prototype._subscribe = function (o) {
  5320. return this.source.subscribe(o);
  5321. };
  5322. ControlledObservable.prototype.request = function (numberOfItems) {
  5323. return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
  5324. };
  5325. return ControlledObservable;
  5326. }(Observable));
  5327. var ControlledSubject = (function (__super__) {
  5328. inherits(ControlledSubject, __super__);
  5329. function ControlledSubject(enableQueue, scheduler) {
  5330. enableQueue == null && (enableQueue = true);
  5331. __super__.call(this);
  5332. this.subject = new Subject();
  5333. this.enableQueue = enableQueue;
  5334. this.queue = enableQueue ? [] : null;
  5335. this.requestedCount = 0;
  5336. this.requestedDisposable = null;
  5337. this.error = null;
  5338. this.hasFailed = false;
  5339. this.hasCompleted = false;
  5340. this.scheduler = scheduler || currentThreadScheduler;
  5341. }
  5342. addProperties(ControlledSubject.prototype, Observer, {
  5343. _subscribe: function (o) {
  5344. return this.subject.subscribe(o);
  5345. },
  5346. onCompleted: function () {
  5347. this.hasCompleted = true;
  5348. if (!this.enableQueue || this.queue.length === 0) {
  5349. this.subject.onCompleted();
  5350. this.disposeCurrentRequest();
  5351. } else {
  5352. this.queue.push(Notification.createOnCompleted());
  5353. }
  5354. },
  5355. onError: function (error) {
  5356. this.hasFailed = true;
  5357. this.error = error;
  5358. if (!this.enableQueue || this.queue.length === 0) {
  5359. this.subject.onError(error);
  5360. this.disposeCurrentRequest();
  5361. } else {
  5362. this.queue.push(Notification.createOnError(error));
  5363. }
  5364. },
  5365. onNext: function (value) {
  5366. if (this.requestedCount <= 0) {
  5367. this.enableQueue && this.queue.push(Notification.createOnNext(value));
  5368. } else {
  5369. (this.requestedCount-- === 0) && this.disposeCurrentRequest();
  5370. this.subject.onNext(value);
  5371. }
  5372. },
  5373. _processRequest: function (numberOfItems) {
  5374. if (this.enableQueue) {
  5375. while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) {
  5376. var first = this.queue.shift();
  5377. first.accept(this.subject);
  5378. if (first.kind === 'N') {
  5379. numberOfItems--;
  5380. } else {
  5381. this.disposeCurrentRequest();
  5382. this.queue = [];
  5383. }
  5384. }
  5385. }
  5386. return numberOfItems;
  5387. },
  5388. request: function (number) {
  5389. this.disposeCurrentRequest();
  5390. var self = this;
  5391. this.requestedDisposable = this.scheduler.schedule(number,
  5392. function(s, i) {
  5393. var remaining = self._processRequest(i);
  5394. var stopped = self.hasCompleted || self.hasFailed;
  5395. if (!stopped && remaining > 0) {
  5396. self.requestedCount = remaining;
  5397. return disposableCreate(function () {
  5398. self.requestedCount = 0;
  5399. });
  5400. // Scheduled item is still in progress. Return a new
  5401. // disposable to allow the request to be interrupted
  5402. // via dispose.
  5403. }
  5404. });
  5405. return this.requestedDisposable;
  5406. },
  5407. disposeCurrentRequest: function () {
  5408. if (this.requestedDisposable) {
  5409. this.requestedDisposable.dispose();
  5410. this.requestedDisposable = null;
  5411. }
  5412. }
  5413. });
  5414. return ControlledSubject;
  5415. }(Observable));
  5416. /**
  5417. * Attaches a controller to the observable sequence with the ability to queue.
  5418. * @example
  5419. * var source = Rx.Observable.interval(100).controlled();
  5420. * source.request(3); // Reads 3 values
  5421. * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request
  5422. * @param {Scheduler} scheduler determines how the requests will be scheduled
  5423. * @returns {Observable} The observable sequence which only propagates values on request.
  5424. */
  5425. observableProto.controlled = function (enableQueue, scheduler) {
  5426. if (enableQueue && isScheduler(enableQueue)) {
  5427. scheduler = enableQueue;
  5428. enableQueue = true;
  5429. }
  5430. if (enableQueue == null) { enableQueue = true; }
  5431. return new ControlledObservable(this, enableQueue, scheduler);
  5432. };
  5433. /**
  5434. * Pipes the existing Observable sequence into a Node.js Stream.
  5435. * @param {Stream} dest The destination Node.js stream.
  5436. * @returns {Stream} The destination stream.
  5437. */
  5438. observableProto.pipe = function (dest) {
  5439. var source = this.pausableBuffered();
  5440. function onDrain() {
  5441. source.resume();
  5442. }
  5443. dest.addListener('drain', onDrain);
  5444. source.subscribe(
  5445. function (x) {
  5446. !dest.write(String(x)) && source.pause();
  5447. },
  5448. function (err) {
  5449. dest.emit('error', err);
  5450. },
  5451. function () {
  5452. // Hack check because STDIO is not closable
  5453. !dest._isStdio && dest.end();
  5454. dest.removeListener('drain', onDrain);
  5455. });
  5456. source.resume();
  5457. return dest;
  5458. };
  5459. var TransduceObserver = (function (__super__) {
  5460. inherits(TransduceObserver, __super__);
  5461. function TransduceObserver(o, xform) {
  5462. this._o = o;
  5463. this._xform = xform;
  5464. __super__.call(this);
  5465. }
  5466. TransduceObserver.prototype.next = function (x) {
  5467. var res = tryCatch(this._xform['@@transducer/step']).call(this._xform, this._o, x);
  5468. if (res === errorObj) { this._o.onError(res.e); }
  5469. };
  5470. TransduceObserver.prototype.error = function (e) { this._o.onError(e); };
  5471. TransduceObserver.prototype.completed = function () {
  5472. this._xform['@@transducer/result'](this._o);
  5473. };
  5474. return TransduceObserver;
  5475. }(AbstractObserver));
  5476. function transformForObserver(o) {
  5477. return {
  5478. '@@transducer/init': function() {
  5479. return o;
  5480. },
  5481. '@@transducer/step': function(obs, input) {
  5482. return obs.onNext(input);
  5483. },
  5484. '@@transducer/result': function(obs) {
  5485. return obs.onCompleted();
  5486. }
  5487. };
  5488. }
  5489. /**
  5490. * Executes a transducer to transform the observable sequence
  5491. * @param {Transducer} transducer A transducer to execute
  5492. * @returns {Observable} An Observable sequence containing the results from the transducer.
  5493. */
  5494. observableProto.transduce = function(transducer) {
  5495. var source = this;
  5496. return new AnonymousObservable(function(o) {
  5497. var xform = transducer(transformForObserver(o));
  5498. return source.subscribe(new TransduceObserver(o, xform));
  5499. }, source);
  5500. };
  5501. var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
  5502. inherits(AnonymousObservable, __super__);
  5503. // Fix subscriber to check for undefined or function returned to decorate as Disposable
  5504. function fixSubscriber(subscriber) {
  5505. return subscriber && isFunction(subscriber.dispose) ? subscriber :
  5506. isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
  5507. }
  5508. function setDisposable(s, state) {
  5509. var ado = state[0], self = state[1];
  5510. var sub = tryCatch(self.__subscribe).call(self, ado);
  5511. if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
  5512. ado.setDisposable(fixSubscriber(sub));
  5513. }
  5514. function AnonymousObservable(subscribe, parent) {
  5515. this.source = parent;
  5516. this.__subscribe = subscribe;
  5517. __super__.call(this);
  5518. }
  5519. AnonymousObservable.prototype._subscribe = function (o) {
  5520. var ado = new AutoDetachObserver(o), state = [ado, this];
  5521. if (currentThreadScheduler.scheduleRequired()) {
  5522. currentThreadScheduler.schedule(state, setDisposable);
  5523. } else {
  5524. setDisposable(null, state);
  5525. }
  5526. return ado;
  5527. };
  5528. return AnonymousObservable;
  5529. }(Observable));
  5530. var AutoDetachObserver = (function (__super__) {
  5531. inherits(AutoDetachObserver, __super__);
  5532. function AutoDetachObserver(observer) {
  5533. __super__.call(this);
  5534. this.observer = observer;
  5535. this.m = new SingleAssignmentDisposable();
  5536. }
  5537. var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
  5538. AutoDetachObserverPrototype.next = function (value) {
  5539. var result = tryCatch(this.observer.onNext).call(this.observer, value);
  5540. if (result === errorObj) {
  5541. this.dispose();
  5542. thrower(result.e);
  5543. }
  5544. };
  5545. AutoDetachObserverPrototype.error = function (err) {
  5546. var result = tryCatch(this.observer.onError).call(this.observer, err);
  5547. this.dispose();
  5548. result === errorObj && thrower(result.e);
  5549. };
  5550. AutoDetachObserverPrototype.completed = function () {
  5551. var result = tryCatch(this.observer.onCompleted).call(this.observer);
  5552. this.dispose();
  5553. result === errorObj && thrower(result.e);
  5554. };
  5555. AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
  5556. AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
  5557. AutoDetachObserverPrototype.dispose = function () {
  5558. __super__.prototype.dispose.call(this);
  5559. this.m.dispose();
  5560. };
  5561. return AutoDetachObserver;
  5562. }(AbstractObserver));
  5563. var InnerSubscription = function (s, o) {
  5564. this._s = s;
  5565. this._o = o;
  5566. };
  5567. InnerSubscription.prototype.dispose = function () {
  5568. if (!this._s.isDisposed && this._o !== null) {
  5569. var idx = this._s.observers.indexOf(this._o);
  5570. this._s.observers.splice(idx, 1);
  5571. this._o = null;
  5572. }
  5573. };
  5574. /**
  5575. * Represents an object that is both an observable sequence as well as an observer.
  5576. * Each notification is broadcasted to all subscribed observers.
  5577. */
  5578. var Subject = Rx.Subject = (function (__super__) {
  5579. inherits(Subject, __super__);
  5580. function Subject() {
  5581. __super__.call(this);
  5582. this.isDisposed = false;
  5583. this.isStopped = false;
  5584. this.observers = [];
  5585. this.hasError = false;
  5586. }
  5587. addProperties(Subject.prototype, Observer.prototype, {
  5588. _subscribe: function (o) {
  5589. checkDisposed(this);
  5590. if (!this.isStopped) {
  5591. this.observers.push(o);
  5592. return new InnerSubscription(this, o);
  5593. }
  5594. if (this.hasError) {
  5595. o.onError(this.error);
  5596. return disposableEmpty;
  5597. }
  5598. o.onCompleted();
  5599. return disposableEmpty;
  5600. },
  5601. /**
  5602. * Indicates whether the subject has observers subscribed to it.
  5603. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  5604. */
  5605. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  5606. /**
  5607. * Notifies all subscribed observers about the end of the sequence.
  5608. */
  5609. onCompleted: function () {
  5610. checkDisposed(this);
  5611. if (!this.isStopped) {
  5612. this.isStopped = true;
  5613. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5614. os[i].onCompleted();
  5615. }
  5616. this.observers.length = 0;
  5617. }
  5618. },
  5619. /**
  5620. * Notifies all subscribed observers about the exception.
  5621. * @param {Mixed} error The exception to send to all observers.
  5622. */
  5623. onError: function (error) {
  5624. checkDisposed(this);
  5625. if (!this.isStopped) {
  5626. this.isStopped = true;
  5627. this.error = error;
  5628. this.hasError = true;
  5629. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5630. os[i].onError(error);
  5631. }
  5632. this.observers.length = 0;
  5633. }
  5634. },
  5635. /**
  5636. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  5637. * @param {Mixed} value The value to send to all observers.
  5638. */
  5639. onNext: function (value) {
  5640. checkDisposed(this);
  5641. if (!this.isStopped) {
  5642. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5643. os[i].onNext(value);
  5644. }
  5645. }
  5646. },
  5647. /**
  5648. * Unsubscribe all observers and release resources.
  5649. */
  5650. dispose: function () {
  5651. this.isDisposed = true;
  5652. this.observers = null;
  5653. }
  5654. });
  5655. /**
  5656. * Creates a subject from the specified observer and observable.
  5657. * @param {Observer} observer The observer used to send messages to the subject.
  5658. * @param {Observable} observable The observable used to subscribe to messages sent from the subject.
  5659. * @returns {Subject} Subject implemented using the given observer and observable.
  5660. */
  5661. Subject.create = function (observer, observable) {
  5662. return new AnonymousSubject(observer, observable);
  5663. };
  5664. return Subject;
  5665. }(Observable));
  5666. /**
  5667. * Represents the result of an asynchronous operation.
  5668. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
  5669. */
  5670. var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
  5671. inherits(AsyncSubject, __super__);
  5672. /**
  5673. * Creates a subject that can only receive one value and that value is cached for all future observations.
  5674. * @constructor
  5675. */
  5676. function AsyncSubject() {
  5677. __super__.call(this);
  5678. this.isDisposed = false;
  5679. this.isStopped = false;
  5680. this.hasValue = false;
  5681. this.observers = [];
  5682. this.hasError = false;
  5683. }
  5684. addProperties(AsyncSubject.prototype, Observer.prototype, {
  5685. _subscribe: function (o) {
  5686. checkDisposed(this);
  5687. if (!this.isStopped) {
  5688. this.observers.push(o);
  5689. return new InnerSubscription(this, o);
  5690. }
  5691. if (this.hasError) {
  5692. o.onError(this.error);
  5693. } else if (this.hasValue) {
  5694. o.onNext(this.value);
  5695. o.onCompleted();
  5696. } else {
  5697. o.onCompleted();
  5698. }
  5699. return disposableEmpty;
  5700. },
  5701. /**
  5702. * Indicates whether the subject has observers subscribed to it.
  5703. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  5704. */
  5705. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  5706. /**
  5707. * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
  5708. */
  5709. onCompleted: function () {
  5710. var i, len;
  5711. checkDisposed(this);
  5712. if (!this.isStopped) {
  5713. this.isStopped = true;
  5714. var os = cloneArray(this.observers), len = os.length;
  5715. if (this.hasValue) {
  5716. for (i = 0; i < len; i++) {
  5717. var o = os[i];
  5718. o.onNext(this.value);
  5719. o.onCompleted();
  5720. }
  5721. } else {
  5722. for (i = 0; i < len; i++) {
  5723. os[i].onCompleted();
  5724. }
  5725. }
  5726. this.observers.length = 0;
  5727. }
  5728. },
  5729. /**
  5730. * Notifies all subscribed observers about the error.
  5731. * @param {Mixed} error The Error to send to all observers.
  5732. */
  5733. onError: function (error) {
  5734. checkDisposed(this);
  5735. if (!this.isStopped) {
  5736. this.isStopped = true;
  5737. this.hasError = true;
  5738. this.error = error;
  5739. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5740. os[i].onError(error);
  5741. }
  5742. this.observers.length = 0;
  5743. }
  5744. },
  5745. /**
  5746. * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
  5747. * @param {Mixed} value The value to store in the subject.
  5748. */
  5749. onNext: function (value) {
  5750. checkDisposed(this);
  5751. if (this.isStopped) { return; }
  5752. this.value = value;
  5753. this.hasValue = true;
  5754. },
  5755. /**
  5756. * Unsubscribe all observers and release resources.
  5757. */
  5758. dispose: function () {
  5759. this.isDisposed = true;
  5760. this.observers = null;
  5761. this.error = null;
  5762. this.value = null;
  5763. }
  5764. });
  5765. return AsyncSubject;
  5766. }(Observable));
  5767. var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
  5768. inherits(AnonymousSubject, __super__);
  5769. function AnonymousSubject(observer, observable) {
  5770. this.observer = observer;
  5771. this.observable = observable;
  5772. __super__.call(this);
  5773. }
  5774. addProperties(AnonymousSubject.prototype, Observer.prototype, {
  5775. _subscribe: function (o) {
  5776. return this.observable.subscribe(o);
  5777. },
  5778. onCompleted: function () {
  5779. this.observer.onCompleted();
  5780. },
  5781. onError: function (error) {
  5782. this.observer.onError(error);
  5783. },
  5784. onNext: function (value) {
  5785. this.observer.onNext(value);
  5786. }
  5787. });
  5788. return AnonymousSubject;
  5789. }(Observable));
  5790. /**
  5791. * Represents a value that changes over time.
  5792. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
  5793. */
  5794. var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
  5795. inherits(BehaviorSubject, __super__);
  5796. function BehaviorSubject(value) {
  5797. __super__.call(this);
  5798. this.value = value;
  5799. this.observers = [];
  5800. this.isDisposed = false;
  5801. this.isStopped = false;
  5802. this.hasError = false;
  5803. }
  5804. addProperties(BehaviorSubject.prototype, Observer.prototype, {
  5805. _subscribe: function (o) {
  5806. checkDisposed(this);
  5807. if (!this.isStopped) {
  5808. this.observers.push(o);
  5809. o.onNext(this.value);
  5810. return new InnerSubscription(this, o);
  5811. }
  5812. if (this.hasError) {
  5813. o.onError(this.error);
  5814. } else {
  5815. o.onCompleted();
  5816. }
  5817. return disposableEmpty;
  5818. },
  5819. /**
  5820. * Gets the current value or throws an exception.
  5821. * Value is frozen after onCompleted is called.
  5822. * After onError is called always throws the specified exception.
  5823. * An exception is always thrown after dispose is called.
  5824. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
  5825. */
  5826. getValue: function () {
  5827. checkDisposed(this);
  5828. if (this.hasError) { thrower(this.error); }
  5829. return this.value;
  5830. },
  5831. /**
  5832. * Indicates whether the subject has observers subscribed to it.
  5833. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  5834. */
  5835. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  5836. /**
  5837. * Notifies all subscribed observers about the end of the sequence.
  5838. */
  5839. onCompleted: function () {
  5840. checkDisposed(this);
  5841. if (this.isStopped) { return; }
  5842. this.isStopped = true;
  5843. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5844. os[i].onCompleted();
  5845. }
  5846. this.observers.length = 0;
  5847. },
  5848. /**
  5849. * Notifies all subscribed observers about the exception.
  5850. * @param {Mixed} error The exception to send to all observers.
  5851. */
  5852. onError: function (error) {
  5853. checkDisposed(this);
  5854. if (this.isStopped) { return; }
  5855. this.isStopped = true;
  5856. this.hasError = true;
  5857. this.error = error;
  5858. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5859. os[i].onError(error);
  5860. }
  5861. this.observers.length = 0;
  5862. },
  5863. /**
  5864. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  5865. * @param {Mixed} value The value to send to all observers.
  5866. */
  5867. onNext: function (value) {
  5868. checkDisposed(this);
  5869. if (this.isStopped) { return; }
  5870. this.value = value;
  5871. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5872. os[i].onNext(value);
  5873. }
  5874. },
  5875. /**
  5876. * Unsubscribe all observers and release resources.
  5877. */
  5878. dispose: function () {
  5879. this.isDisposed = true;
  5880. this.observers = null;
  5881. this.value = null;
  5882. this.error = null;
  5883. }
  5884. });
  5885. return BehaviorSubject;
  5886. }(Observable));
  5887. /**
  5888. * Represents an object that is both an observable sequence as well as an observer.
  5889. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
  5890. */
  5891. var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
  5892. var maxSafeInteger = Math.pow(2, 53) - 1;
  5893. function createRemovableDisposable(subject, observer) {
  5894. return disposableCreate(function () {
  5895. observer.dispose();
  5896. !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
  5897. });
  5898. }
  5899. inherits(ReplaySubject, __super__);
  5900. /**
  5901. * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
  5902. * @param {Number} [bufferSize] Maximum element count of the replay buffer.
  5903. * @param {Number} [windowSize] Maximum time length of the replay buffer.
  5904. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
  5905. */
  5906. function ReplaySubject(bufferSize, windowSize, scheduler) {
  5907. this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
  5908. this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
  5909. this.scheduler = scheduler || currentThreadScheduler;
  5910. this.q = [];
  5911. this.observers = [];
  5912. this.isStopped = false;
  5913. this.isDisposed = false;
  5914. this.hasError = false;
  5915. this.error = null;
  5916. __super__.call(this);
  5917. }
  5918. addProperties(ReplaySubject.prototype, Observer.prototype, {
  5919. _subscribe: function (o) {
  5920. checkDisposed(this);
  5921. var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so);
  5922. this._trim(this.scheduler.now());
  5923. this.observers.push(so);
  5924. for (var i = 0, len = this.q.length; i < len; i++) {
  5925. so.onNext(this.q[i].value);
  5926. }
  5927. if (this.hasError) {
  5928. so.onError(this.error);
  5929. } else if (this.isStopped) {
  5930. so.onCompleted();
  5931. }
  5932. so.ensureActive();
  5933. return subscription;
  5934. },
  5935. /**
  5936. * Indicates whether the subject has observers subscribed to it.
  5937. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  5938. */
  5939. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  5940. _trim: function (now) {
  5941. while (this.q.length > this.bufferSize) {
  5942. this.q.shift();
  5943. }
  5944. while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
  5945. this.q.shift();
  5946. }
  5947. },
  5948. /**
  5949. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  5950. * @param {Mixed} value The value to send to all observers.
  5951. */
  5952. onNext: function (value) {
  5953. checkDisposed(this);
  5954. if (this.isStopped) { return; }
  5955. var now = this.scheduler.now();
  5956. this.q.push({ interval: now, value: value });
  5957. this._trim(now);
  5958. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5959. var observer = os[i];
  5960. observer.onNext(value);
  5961. observer.ensureActive();
  5962. }
  5963. },
  5964. /**
  5965. * Notifies all subscribed observers about the exception.
  5966. * @param {Mixed} error The exception to send to all observers.
  5967. */
  5968. onError: function (error) {
  5969. checkDisposed(this);
  5970. if (this.isStopped) { return; }
  5971. this.isStopped = true;
  5972. this.error = error;
  5973. this.hasError = true;
  5974. var now = this.scheduler.now();
  5975. this._trim(now);
  5976. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5977. var observer = os[i];
  5978. observer.onError(error);
  5979. observer.ensureActive();
  5980. }
  5981. this.observers.length = 0;
  5982. },
  5983. /**
  5984. * Notifies all subscribed observers about the end of the sequence.
  5985. */
  5986. onCompleted: function () {
  5987. checkDisposed(this);
  5988. if (this.isStopped) { return; }
  5989. this.isStopped = true;
  5990. var now = this.scheduler.now();
  5991. this._trim(now);
  5992. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  5993. var observer = os[i];
  5994. observer.onCompleted();
  5995. observer.ensureActive();
  5996. }
  5997. this.observers.length = 0;
  5998. },
  5999. /**
  6000. * Unsubscribe all observers and release resources.
  6001. */
  6002. dispose: function () {
  6003. this.isDisposed = true;
  6004. this.observers = null;
  6005. }
  6006. });
  6007. return ReplaySubject;
  6008. }(Observable));
  6009. /**
  6010. * Used to pause and resume streams.
  6011. */
  6012. Rx.Pauser = (function (__super__) {
  6013. inherits(Pauser, __super__);
  6014. function Pauser() {
  6015. __super__.call(this);
  6016. }
  6017. /**
  6018. * Pauses the underlying sequence.
  6019. */
  6020. Pauser.prototype.pause = function () { this.onNext(false); };
  6021. /**
  6022. * Resumes the underlying sequence.
  6023. */
  6024. Pauser.prototype.resume = function () { this.onNext(true); };
  6025. return Pauser;
  6026. }(Subject));
  6027. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  6028. root.Rx = Rx;
  6029. define(function() {
  6030. return Rx;
  6031. });
  6032. } else if (freeExports && freeModule) {
  6033. // in Node.js or RingoJS
  6034. if (moduleExports) {
  6035. (freeModule.exports = Rx).Rx = Rx;
  6036. } else {
  6037. freeExports.Rx = Rx;
  6038. }
  6039. } else {
  6040. // in a browser or Rhino
  6041. root.Rx = Rx;
  6042. }
  6043. // All code before this point will be filtered from stack traces.
  6044. var rEndingLine = captureLine();
  6045. }.call(this));