Rx.js 773 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262
  1. /**
  2. @license
  3. Apache License
  4. Version 2.0, January 2004
  5. http://www.apache.org/licenses/
  6. TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
  7. 1. Definitions.
  8. "License" shall mean the terms and conditions for use, reproduction,
  9. and distribution as defined by Sections 1 through 9 of this document.
  10. "Licensor" shall mean the copyright owner or entity authorized by
  11. the copyright owner that is granting the License.
  12. "Legal Entity" shall mean the union of the acting entity and all
  13. other entities that control, are controlled by, or are under common
  14. control with that entity. For the purposes of this definition,
  15. "control" means (i) the power, direct or indirect, to cause the
  16. direction or management of such entity, whether by contract or
  17. otherwise, or (ii) ownership of fifty percent (50%) or more of the
  18. outstanding shares, or (iii) beneficial ownership of such entity.
  19. "You" (or "Your") shall mean an individual or Legal Entity
  20. exercising permissions granted by this License.
  21. "Source" form shall mean the preferred form for making modifications,
  22. including but not limited to software source code, documentation
  23. source, and configuration files.
  24. "Object" form shall mean any form resulting from mechanical
  25. transformation or translation of a Source form, including but
  26. not limited to compiled object code, generated documentation,
  27. and conversions to other media types.
  28. "Work" shall mean the work of authorship, whether in Source or
  29. Object form, made available under the License, as indicated by a
  30. copyright notice that is included in or attached to the work
  31. (an example is provided in the Appendix below).
  32. "Derivative Works" shall mean any work, whether in Source or Object
  33. form, that is based on (or derived from) the Work and for which the
  34. editorial revisions, annotations, elaborations, or other modifications
  35. represent, as a whole, an original work of authorship. For the purposes
  36. of this License, Derivative Works shall not include works that remain
  37. separable from, or merely link (or bind by name) to the interfaces of,
  38. the Work and Derivative Works thereof.
  39. "Contribution" shall mean any work of authorship, including
  40. the original version of the Work and any modifications or additions
  41. to that Work or Derivative Works thereof, that is intentionally
  42. submitted to Licensor for inclusion in the Work by the copyright owner
  43. or by an individual or Legal Entity authorized to submit on behalf of
  44. the copyright owner. For the purposes of this definition, "submitted"
  45. means any form of electronic, verbal, or written communication sent
  46. to the Licensor or its representatives, including but not limited to
  47. communication on electronic mailing lists, source code control systems,
  48. and issue tracking systems that are managed by, or on behalf of, the
  49. Licensor for the purpose of discussing and improving the Work, but
  50. excluding communication that is conspicuously marked or otherwise
  51. designated in writing by the copyright owner as "Not a Contribution."
  52. "Contributor" shall mean Licensor and any individual or Legal Entity
  53. on behalf of whom a Contribution has been received by Licensor and
  54. subsequently incorporated within the Work.
  55. 2. Grant of Copyright License. Subject to the terms and conditions of
  56. this License, each Contributor hereby grants to You a perpetual,
  57. worldwide, non-exclusive, no-charge, royalty-free, irrevocable
  58. copyright license to reproduce, prepare Derivative Works of,
  59. publicly display, publicly perform, sublicense, and distribute the
  60. Work and such Derivative Works in Source or Object form.
  61. 3. Grant of Patent License. Subject to the terms and conditions of
  62. this License, each Contributor hereby grants to You a perpetual,
  63. worldwide, non-exclusive, no-charge, royalty-free, irrevocable
  64. (except as stated in this section) patent license to make, have made,
  65. use, offer to sell, sell, import, and otherwise transfer the Work,
  66. where such license applies only to those patent claims licensable
  67. by such Contributor that are necessarily infringed by their
  68. Contribution(s) alone or by combination of their Contribution(s)
  69. with the Work to which such Contribution(s) was submitted. If You
  70. institute patent litigation against any entity (including a
  71. cross-claim or counterclaim in a lawsuit) alleging that the Work
  72. or a Contribution incorporated within the Work constitutes direct
  73. or contributory patent infringement, then any patent licenses
  74. granted to You under this License for that Work shall terminate
  75. as of the date such litigation is filed.
  76. 4. Redistribution. You may reproduce and distribute copies of the
  77. Work or Derivative Works thereof in any medium, with or without
  78. modifications, and in Source or Object form, provided that You
  79. meet the following conditions:
  80. (a) You must give any other recipients of the Work or
  81. Derivative Works a copy of this License; and
  82. (b) You must cause any modified files to carry prominent notices
  83. stating that You changed the files; and
  84. (c) You must retain, in the Source form of any Derivative Works
  85. that You distribute, all copyright, patent, trademark, and
  86. attribution notices from the Source form of the Work,
  87. excluding those notices that do not pertain to any part of
  88. the Derivative Works; and
  89. (d) If the Work includes a "NOTICE" text file as part of its
  90. distribution, then any Derivative Works that You distribute must
  91. include a readable copy of the attribution notices contained
  92. within such NOTICE file, excluding those notices that do not
  93. pertain to any part of the Derivative Works, in at least one
  94. of the following places: within a NOTICE text file distributed
  95. as part of the Derivative Works; within the Source form or
  96. documentation, if provided along with the Derivative Works; or,
  97. within a display generated by the Derivative Works, if and
  98. wherever such third-party notices normally appear. The contents
  99. of the NOTICE file are for informational purposes only and
  100. do not modify the License. You may add Your own attribution
  101. notices within Derivative Works that You distribute, alongside
  102. or as an addendum to the NOTICE text from the Work, provided
  103. that such additional attribution notices cannot be construed
  104. as modifying the License.
  105. You may add Your own copyright statement to Your modifications and
  106. may provide additional or different license terms and conditions
  107. for use, reproduction, or distribution of Your modifications, or
  108. for any such Derivative Works as a whole, provided Your use,
  109. reproduction, and distribution of the Work otherwise complies with
  110. the conditions stated in this License.
  111. 5. Submission of Contributions. Unless You explicitly state otherwise,
  112. any Contribution intentionally submitted for inclusion in the Work
  113. by You to the Licensor shall be under the terms and conditions of
  114. this License, without any additional terms or conditions.
  115. Notwithstanding the above, nothing herein shall supersede or modify
  116. the terms of any separate license agreement you may have executed
  117. with Licensor regarding such Contributions.
  118. 6. Trademarks. This License does not grant permission to use the trade
  119. names, trademarks, service marks, or product names of the Licensor,
  120. except as required for reasonable and customary use in describing the
  121. origin of the Work and reproducing the content of the NOTICE file.
  122. 7. Disclaimer of Warranty. Unless required by applicable law or
  123. agreed to in writing, Licensor provides the Work (and each
  124. Contributor provides its Contributions) on an "AS IS" BASIS,
  125. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  126. implied, including, without limitation, any warranties or conditions
  127. of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
  128. PARTICULAR PURPOSE. You are solely responsible for determining the
  129. appropriateness of using or redistributing the Work and assume any
  130. risks associated with Your exercise of permissions under this License.
  131. 8. Limitation of Liability. In no event and under no legal theory,
  132. whether in tort (including negligence), contract, or otherwise,
  133. unless required by applicable law (such as deliberate and grossly
  134. negligent acts) or agreed to in writing, shall any Contributor be
  135. liable to You for damages, including any direct, indirect, special,
  136. incidental, or consequential damages of any character arising as a
  137. result of this License or out of the use or inability to use the
  138. Work (including but not limited to damages for loss of goodwill,
  139. work stoppage, computer failure or malfunction, or any and all
  140. other commercial damages or losses), even if such Contributor
  141. has been advised of the possibility of such damages.
  142. 9. Accepting Warranty or Additional Liability. While redistributing
  143. the Work or Derivative Works thereof, You may choose to offer,
  144. and charge a fee for, acceptance of support, warranty, indemnity,
  145. or other liability obligations and/or rights consistent with this
  146. License. However, in accepting such obligations, You may act only
  147. on Your own behalf and on Your sole responsibility, not on behalf
  148. of any other Contributor, and only if You agree to indemnify,
  149. defend, and hold each Contributor harmless for any liability
  150. incurred by, or claims asserted against, such Contributor by reason
  151. of your accepting any such warranty or additional liability.
  152. END OF TERMS AND CONDITIONS
  153. APPENDIX: How to apply the Apache License to your work.
  154. To apply the Apache License to your work, attach the following
  155. boilerplate notice, with the fields enclosed by brackets "[]"
  156. replaced with your own identifying information. (Don't include
  157. the brackets!) The text should be enclosed in the appropriate
  158. comment syntax for the file format. We also recommend that a
  159. file or class name and description of purpose be included on the
  160. same "printed page" as the copyright notice for easier
  161. identification within third-party archives.
  162. Copyright (c) 2015-2017 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors
  163. Licensed under the Apache License, Version 2.0 (the "License");
  164. you may not use this file except in compliance with the License.
  165. You may obtain a copy of the License at
  166. http://www.apache.org/licenses/LICENSE-2.0
  167. Unless required by applicable law or agreed to in writing, software
  168. distributed under the License is distributed on an "AS IS" BASIS,
  169. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  170. See the License for the specific language governing permissions and
  171. limitations under the License.
  172. **/
  173. /**
  174. @license
  175. Apache License
  176. Version 2.0, January 2004
  177. http://www.apache.org/licenses/
  178. TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
  179. 1. Definitions.
  180. "License" shall mean the terms and conditions for use, reproduction,
  181. and distribution as defined by Sections 1 through 9 of this document.
  182. "Licensor" shall mean the copyright owner or entity authorized by
  183. the copyright owner that is granting the License.
  184. "Legal Entity" shall mean the union of the acting entity and all
  185. other entities that control, are controlled by, or are under common
  186. control with that entity. For the purposes of this definition,
  187. "control" means (i) the power, direct or indirect, to cause the
  188. direction or management of such entity, whether by contract or
  189. otherwise, or (ii) ownership of fifty percent (50%) or more of the
  190. outstanding shares, or (iii) beneficial ownership of such entity.
  191. "You" (or "Your") shall mean an individual or Legal Entity
  192. exercising permissions granted by this License.
  193. "Source" form shall mean the preferred form for making modifications,
  194. including but not limited to software source code, documentation
  195. source, and configuration files.
  196. "Object" form shall mean any form resulting from mechanical
  197. transformation or translation of a Source form, including but
  198. not limited to compiled object code, generated documentation,
  199. and conversions to other media types.
  200. "Work" shall mean the work of authorship, whether in Source or
  201. Object form, made available under the License, as indicated by a
  202. copyright notice that is included in or attached to the work
  203. (an example is provided in the Appendix below).
  204. "Derivative Works" shall mean any work, whether in Source or Object
  205. form, that is based on (or derived from) the Work and for which the
  206. editorial revisions, annotations, elaborations, or other modifications
  207. represent, as a whole, an original work of authorship. For the purposes
  208. of this License, Derivative Works shall not include works that remain
  209. separable from, or merely link (or bind by name) to the interfaces of,
  210. the Work and Derivative Works thereof.
  211. "Contribution" shall mean any work of authorship, including
  212. the original version of the Work and any modifications or additions
  213. to that Work or Derivative Works thereof, that is intentionally
  214. submitted to Licensor for inclusion in the Work by the copyright owner
  215. or by an individual or Legal Entity authorized to submit on behalf of
  216. the copyright owner. For the purposes of this definition, "submitted"
  217. means any form of electronic, verbal, or written communication sent
  218. to the Licensor or its representatives, including but not limited to
  219. communication on electronic mailing lists, source code control systems,
  220. and issue tracking systems that are managed by, or on behalf of, the
  221. Licensor for the purpose of discussing and improving the Work, but
  222. excluding communication that is conspicuously marked or otherwise
  223. designated in writing by the copyright owner as "Not a Contribution."
  224. "Contributor" shall mean Licensor and any individual or Legal Entity
  225. on behalf of whom a Contribution has been received by Licensor and
  226. subsequently incorporated within the Work.
  227. 2. Grant of Copyright License. Subject to the terms and conditions of
  228. this License, each Contributor hereby grants to You a perpetual,
  229. worldwide, non-exclusive, no-charge, royalty-free, irrevocable
  230. copyright license to reproduce, prepare Derivative Works of,
  231. publicly display, publicly perform, sublicense, and distribute the
  232. Work and such Derivative Works in Source or Object form.
  233. 3. Grant of Patent License. Subject to the terms and conditions of
  234. this License, each Contributor hereby grants to You a perpetual,
  235. worldwide, non-exclusive, no-charge, royalty-free, irrevocable
  236. (except as stated in this section) patent license to make, have made,
  237. use, offer to sell, sell, import, and otherwise transfer the Work,
  238. where such license applies only to those patent claims licensable
  239. by such Contributor that are necessarily infringed by their
  240. Contribution(s) alone or by combination of their Contribution(s)
  241. with the Work to which such Contribution(s) was submitted. If You
  242. institute patent litigation against any entity (including a
  243. cross-claim or counterclaim in a lawsuit) alleging that the Work
  244. or a Contribution incorporated within the Work constitutes direct
  245. or contributory patent infringement, then any patent licenses
  246. granted to You under this License for that Work shall terminate
  247. as of the date such litigation is filed.
  248. 4. Redistribution. You may reproduce and distribute copies of the
  249. Work or Derivative Works thereof in any medium, with or without
  250. modifications, and in Source or Object form, provided that You
  251. meet the following conditions:
  252. (a) You must give any other recipients of the Work or
  253. Derivative Works a copy of this License; and
  254. (b) You must cause any modified files to carry prominent notices
  255. stating that You changed the files; and
  256. (c) You must retain, in the Source form of any Derivative Works
  257. that You distribute, all copyright, patent, trademark, and
  258. attribution notices from the Source form of the Work,
  259. excluding those notices that do not pertain to any part of
  260. the Derivative Works; and
  261. (d) If the Work includes a "NOTICE" text file as part of its
  262. distribution, then any Derivative Works that You distribute must
  263. include a readable copy of the attribution notices contained
  264. within such NOTICE file, excluding those notices that do not
  265. pertain to any part of the Derivative Works, in at least one
  266. of the following places: within a NOTICE text file distributed
  267. as part of the Derivative Works; within the Source form or
  268. documentation, if provided along with the Derivative Works; or,
  269. within a display generated by the Derivative Works, if and
  270. wherever such third-party notices normally appear. The contents
  271. of the NOTICE file are for informational purposes only and
  272. do not modify the License. You may add Your own attribution
  273. notices within Derivative Works that You distribute, alongside
  274. or as an addendum to the NOTICE text from the Work, provided
  275. that such additional attribution notices cannot be construed
  276. as modifying the License.
  277. You may add Your own copyright statement to Your modifications and
  278. may provide additional or different license terms and conditions
  279. for use, reproduction, or distribution of Your modifications, or
  280. for any such Derivative Works as a whole, provided Your use,
  281. reproduction, and distribution of the Work otherwise complies with
  282. the conditions stated in this License.
  283. 5. Submission of Contributions. Unless You explicitly state otherwise,
  284. any Contribution intentionally submitted for inclusion in the Work
  285. by You to the Licensor shall be under the terms and conditions of
  286. this License, without any additional terms or conditions.
  287. Notwithstanding the above, nothing herein shall supersede or modify
  288. the terms of any separate license agreement you may have executed
  289. with Licensor regarding such Contributions.
  290. 6. Trademarks. This License does not grant permission to use the trade
  291. names, trademarks, service marks, or product names of the Licensor,
  292. except as required for reasonable and customary use in describing the
  293. origin of the Work and reproducing the content of the NOTICE file.
  294. 7. Disclaimer of Warranty. Unless required by applicable law or
  295. agreed to in writing, Licensor provides the Work (and each
  296. Contributor provides its Contributions) on an "AS IS" BASIS,
  297. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  298. implied, including, without limitation, any warranties or conditions
  299. of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
  300. PARTICULAR PURPOSE. You are solely responsible for determining the
  301. appropriateness of using or redistributing the Work and assume any
  302. risks associated with Your exercise of permissions under this License.
  303. 8. Limitation of Liability. In no event and under no legal theory,
  304. whether in tort (including negligence), contract, or otherwise,
  305. unless required by applicable law (such as deliberate and grossly
  306. negligent acts) or agreed to in writing, shall any Contributor be
  307. liable to You for damages, including any direct, indirect, special,
  308. incidental, or consequential damages of any character arising as a
  309. result of this License or out of the use or inability to use the
  310. Work (including but not limited to damages for loss of goodwill,
  311. work stoppage, computer failure or malfunction, or any and all
  312. other commercial damages or losses), even if such Contributor
  313. has been advised of the possibility of such damages.
  314. 9. Accepting Warranty or Additional Liability. While redistributing
  315. the Work or Derivative Works thereof, You may choose to offer,
  316. and charge a fee for, acceptance of support, warranty, indemnity,
  317. or other liability obligations and/or rights consistent with this
  318. License. However, in accepting such obligations, You may act only
  319. on Your own behalf and on Your sole responsibility, not on behalf
  320. of any other Contributor, and only if You agree to indemnify,
  321. defend, and hold each Contributor harmless for any liability
  322. incurred by, or claims asserted against, such Contributor by reason
  323. of your accepting any such warranty or additional liability.
  324. END OF TERMS AND CONDITIONS
  325. APPENDIX: How to apply the Apache License to your work.
  326. To apply the Apache License to your work, attach the following
  327. boilerplate notice, with the fields enclosed by brackets "[]"
  328. replaced with your own identifying information. (Don't include
  329. the brackets!) The text should be enclosed in the appropriate
  330. comment syntax for the file format. We also recommend that a
  331. file or class name and description of purpose be included on the
  332. same "printed page" as the copyright notice for easier
  333. identification within third-party archives.
  334. Copyright (c) 2015-2017 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors
  335. Licensed under the Apache License, Version 2.0 (the "License");
  336. you may not use this file except in compliance with the License.
  337. You may obtain a copy of the License at
  338. http://www.apache.org/licenses/LICENSE-2.0
  339. Unless required by applicable law or agreed to in writing, software
  340. distributed under the License is distributed on an "AS IS" BASIS,
  341. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  342. See the License for the specific language governing permissions and
  343. limitations under the License.
  344. **/
  345. (function (global, factory) {
  346. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  347. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  348. (factory((global.Rx = global.Rx || {})));
  349. }(this, (function (exports) { 'use strict';
  350. /*! *****************************************************************************
  351. Copyright (c) Microsoft Corporation. All rights reserved.
  352. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  353. this file except in compliance with the License. You may obtain a copy of the
  354. License at http://www.apache.org/licenses/LICENSE-2.0
  355. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  356. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  357. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  358. MERCHANTABLITY OR NON-INFRINGEMENT.
  359. See the Apache Version 2.0 License for specific language governing permissions
  360. and limitations under the License.
  361. ***************************************************************************** */
  362. /* global Reflect, Promise */
  363. var extendStatics = Object.setPrototypeOf ||
  364. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  365. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  366. function __extends(d, b) {
  367. extendStatics(d, b);
  368. function __() { this.constructor = d; }
  369. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  370. }
  371. function __values(o) {
  372. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  373. if (m) return m.call(o);
  374. return {
  375. next: function () {
  376. if (o && i >= o.length) o = void 0;
  377. return { value: o && o[i++], done: !o };
  378. }
  379. };
  380. }
  381. function __read(o, n) {
  382. var m = typeof Symbol === "function" && o[Symbol.iterator];
  383. if (!m) return o;
  384. var i = m.call(o), r, ar = [], e;
  385. try {
  386. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  387. }
  388. catch (error) { e = { error: error }; }
  389. finally {
  390. try {
  391. if (r && !r.done && (m = i["return"])) m.call(i);
  392. }
  393. finally { if (e) throw e.error; }
  394. }
  395. return ar;
  396. }
  397. function __await(v) {
  398. return this instanceof __await ? (this.v = v, this) : new __await(v);
  399. }
  400. // CommonJS / Node have global context exposed as "global" variable.
  401. // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
  402. // the global "global" var for now.
  403. var __window = typeof window !== 'undefined' && window;
  404. var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  405. self instanceof WorkerGlobalScope && self;
  406. var __global = typeof global !== 'undefined' && global;
  407. var _root = __window || __global || __self;
  408. // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
  409. // This is needed when used with angular/tsickle which inserts a goog.module statement.
  410. // Wrap in IIFE
  411. (function () {
  412. if (!_root) {
  413. throw new Error('RxJS could not find any global context (window, self, global)');
  414. }
  415. })();
  416. function isFunction(x) {
  417. return typeof x === 'function';
  418. }
  419. var isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
  420. function isObject(x) {
  421. return x != null && typeof x === 'object';
  422. }
  423. // typeof any so that it we don't have to cast when comparing a result to the error object
  424. var errorObject = { e: {} };
  425. var tryCatchTarget;
  426. function tryCatcher() {
  427. try {
  428. return tryCatchTarget.apply(this, arguments);
  429. }
  430. catch (e) {
  431. errorObject.e = e;
  432. return errorObject;
  433. }
  434. }
  435. function tryCatch(fn) {
  436. tryCatchTarget = fn;
  437. return tryCatcher;
  438. }
  439. /**
  440. * An error thrown when one or more errors have occurred during the
  441. * `unsubscribe` of a {@link Subscription}.
  442. */
  443. var UnsubscriptionError = (function (_super) {
  444. __extends(UnsubscriptionError, _super);
  445. function UnsubscriptionError(errors) {
  446. _super.call(this);
  447. this.errors = errors;
  448. var err = Error.call(this, errors ?
  449. errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : '');
  450. this.name = err.name = 'UnsubscriptionError';
  451. this.stack = err.stack;
  452. this.message = err.message;
  453. }
  454. return UnsubscriptionError;
  455. }(Error));
  456. /**
  457. * Represents a disposable resource, such as the execution of an Observable. A
  458. * Subscription has one important method, `unsubscribe`, that takes no argument
  459. * and just disposes the resource held by the subscription.
  460. *
  461. * Additionally, subscriptions may be grouped together through the `add()`
  462. * method, which will attach a child Subscription to the current Subscription.
  463. * When a Subscription is unsubscribed, all its children (and its grandchildren)
  464. * will be unsubscribed as well.
  465. *
  466. * @class Subscription
  467. */
  468. var Subscription = (function () {
  469. /**
  470. * @param {function(): void} [unsubscribe] A function describing how to
  471. * perform the disposal of resources when the `unsubscribe` method is called.
  472. */
  473. function Subscription(unsubscribe) {
  474. /**
  475. * A flag to indicate whether this Subscription has already been unsubscribed.
  476. * @type {boolean}
  477. */
  478. this.closed = false;
  479. this._parent = null;
  480. this._parents = null;
  481. this._subscriptions = null;
  482. if (unsubscribe) {
  483. this._unsubscribe = unsubscribe;
  484. }
  485. }
  486. /**
  487. * Disposes the resources held by the subscription. May, for instance, cancel
  488. * an ongoing Observable execution or cancel any other type of work that
  489. * started when the Subscription was created.
  490. * @return {void}
  491. */
  492. Subscription.prototype.unsubscribe = function () {
  493. var hasErrors = false;
  494. var errors;
  495. if (this.closed) {
  496. return;
  497. }
  498. var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
  499. this.closed = true;
  500. this._parent = null;
  501. this._parents = null;
  502. // null out _subscriptions first so any child subscriptions that attempt
  503. // to remove themselves from this subscription will noop
  504. this._subscriptions = null;
  505. var index = -1;
  506. var len = _parents ? _parents.length : 0;
  507. // if this._parent is null, then so is this._parents, and we
  508. // don't have to remove ourselves from any parent subscriptions.
  509. while (_parent) {
  510. _parent.remove(this);
  511. // if this._parents is null or index >= len,
  512. // then _parent is set to null, and the loop exits
  513. _parent = ++index < len && _parents[index] || null;
  514. }
  515. if (isFunction(_unsubscribe)) {
  516. var trial = tryCatch(_unsubscribe).call(this);
  517. if (trial === errorObject) {
  518. hasErrors = true;
  519. errors = errors || (errorObject.e instanceof UnsubscriptionError ?
  520. flattenUnsubscriptionErrors(errorObject.e.errors) : [errorObject.e]);
  521. }
  522. }
  523. if (isArray(_subscriptions)) {
  524. index = -1;
  525. len = _subscriptions.length;
  526. while (++index < len) {
  527. var sub = _subscriptions[index];
  528. if (isObject(sub)) {
  529. var trial = tryCatch(sub.unsubscribe).call(sub);
  530. if (trial === errorObject) {
  531. hasErrors = true;
  532. errors = errors || [];
  533. var err = errorObject.e;
  534. if (err instanceof UnsubscriptionError) {
  535. errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
  536. }
  537. else {
  538. errors.push(err);
  539. }
  540. }
  541. }
  542. }
  543. }
  544. if (hasErrors) {
  545. throw new UnsubscriptionError(errors);
  546. }
  547. };
  548. /**
  549. * Adds a tear down to be called during the unsubscribe() of this
  550. * Subscription.
  551. *
  552. * If the tear down being added is a subscription that is already
  553. * unsubscribed, is the same reference `add` is being called on, or is
  554. * `Subscription.EMPTY`, it will not be added.
  555. *
  556. * If this subscription is already in an `closed` state, the passed
  557. * tear down logic will be executed immediately.
  558. *
  559. * @param {TeardownLogic} teardown The additional logic to execute on
  560. * teardown.
  561. * @return {Subscription} Returns the Subscription used or created to be
  562. * added to the inner subscriptions list. This Subscription can be used with
  563. * `remove()` to remove the passed teardown logic from the inner subscriptions
  564. * list.
  565. */
  566. Subscription.prototype.add = function (teardown) {
  567. if (!teardown || (teardown === Subscription.EMPTY)) {
  568. return Subscription.EMPTY;
  569. }
  570. if (teardown === this) {
  571. return this;
  572. }
  573. var subscription = teardown;
  574. switch (typeof teardown) {
  575. case 'function':
  576. subscription = new Subscription(teardown);
  577. case 'object':
  578. if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
  579. return subscription;
  580. }
  581. else if (this.closed) {
  582. subscription.unsubscribe();
  583. return subscription;
  584. }
  585. else if (typeof subscription._addParent !== 'function' /* quack quack */) {
  586. var tmp = subscription;
  587. subscription = new Subscription();
  588. subscription._subscriptions = [tmp];
  589. }
  590. break;
  591. default:
  592. throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
  593. }
  594. var subscriptions = this._subscriptions || (this._subscriptions = []);
  595. subscriptions.push(subscription);
  596. subscription._addParent(this);
  597. return subscription;
  598. };
  599. /**
  600. * Removes a Subscription from the internal list of subscriptions that will
  601. * unsubscribe during the unsubscribe process of this Subscription.
  602. * @param {Subscription} subscription The subscription to remove.
  603. * @return {void}
  604. */
  605. Subscription.prototype.remove = function (subscription) {
  606. var subscriptions = this._subscriptions;
  607. if (subscriptions) {
  608. var subscriptionIndex = subscriptions.indexOf(subscription);
  609. if (subscriptionIndex !== -1) {
  610. subscriptions.splice(subscriptionIndex, 1);
  611. }
  612. }
  613. };
  614. Subscription.prototype._addParent = function (parent) {
  615. var _a = this, _parent = _a._parent, _parents = _a._parents;
  616. if (!_parent || _parent === parent) {
  617. // If we don't have a parent, or the new parent is the same as the
  618. // current parent, then set this._parent to the new parent.
  619. this._parent = parent;
  620. }
  621. else if (!_parents) {
  622. // If there's already one parent, but not multiple, allocate an Array to
  623. // store the rest of the parent Subscriptions.
  624. this._parents = [parent];
  625. }
  626. else if (_parents.indexOf(parent) === -1) {
  627. // Only add the new parent to the _parents list if it's not already there.
  628. _parents.push(parent);
  629. }
  630. };
  631. Subscription.EMPTY = (function (empty) {
  632. empty.closed = true;
  633. return empty;
  634. }(new Subscription()));
  635. return Subscription;
  636. }());
  637. function flattenUnsubscriptionErrors(errors) {
  638. return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);
  639. }
  640. var empty = {
  641. closed: true,
  642. next: function (value) { },
  643. error: function (err) { throw err; },
  644. complete: function () { }
  645. };
  646. var Symbol$2 = _root.Symbol;
  647. var rxSubscriber = (typeof Symbol$2 === 'function' && typeof Symbol$2.for === 'function') ?
  648. Symbol$2.for('rxSubscriber') : '@@rxSubscriber';
  649. /**
  650. * @deprecated use rxSubscriber instead
  651. */
  652. /**
  653. * Implements the {@link Observer} interface and extends the
  654. * {@link Subscription} class. While the {@link Observer} is the public API for
  655. * consuming the values of an {@link Observable}, all Observers get converted to
  656. * a Subscriber, in order to provide Subscription-like capabilities such as
  657. * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
  658. * implementing operators, but it is rarely used as a public API.
  659. *
  660. * @class Subscriber<T>
  661. */
  662. var Subscriber = (function (_super) {
  663. __extends(Subscriber, _super);
  664. /**
  665. * @param {Observer|function(value: T): void} [destinationOrNext] A partially
  666. * defined Observer or a `next` callback function.
  667. * @param {function(e: ?any): void} [error] The `error` callback of an
  668. * Observer.
  669. * @param {function(): void} [complete] The `complete` callback of an
  670. * Observer.
  671. */
  672. function Subscriber(destinationOrNext, error, complete) {
  673. _super.call(this);
  674. this.syncErrorValue = null;
  675. this.syncErrorThrown = false;
  676. this.syncErrorThrowable = false;
  677. this.isStopped = false;
  678. switch (arguments.length) {
  679. case 0:
  680. this.destination = empty;
  681. break;
  682. case 1:
  683. if (!destinationOrNext) {
  684. this.destination = empty;
  685. break;
  686. }
  687. if (typeof destinationOrNext === 'object') {
  688. // HACK(benlesh): To resolve an issue where Node users may have multiple
  689. // copies of rxjs in their node_modules directory.
  690. if (isTrustedSubscriber(destinationOrNext)) {
  691. var trustedSubscriber = destinationOrNext[rxSubscriber]();
  692. this.syncErrorThrowable = trustedSubscriber.syncErrorThrowable;
  693. this.destination = trustedSubscriber;
  694. trustedSubscriber.add(this);
  695. }
  696. else {
  697. this.syncErrorThrowable = true;
  698. this.destination = new SafeSubscriber(this, destinationOrNext);
  699. }
  700. break;
  701. }
  702. default:
  703. this.syncErrorThrowable = true;
  704. this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
  705. break;
  706. }
  707. }
  708. Subscriber.prototype[rxSubscriber] = function () { return this; };
  709. /**
  710. * A static factory for a Subscriber, given a (potentially partial) definition
  711. * of an Observer.
  712. * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
  713. * @param {function(e: ?any): void} [error] The `error` callback of an
  714. * Observer.
  715. * @param {function(): void} [complete] The `complete` callback of an
  716. * Observer.
  717. * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
  718. * Observer represented by the given arguments.
  719. */
  720. Subscriber.create = function (next, error, complete) {
  721. var subscriber = new Subscriber(next, error, complete);
  722. subscriber.syncErrorThrowable = false;
  723. return subscriber;
  724. };
  725. /**
  726. * The {@link Observer} callback to receive notifications of type `next` from
  727. * the Observable, with a value. The Observable may call this method 0 or more
  728. * times.
  729. * @param {T} [value] The `next` value.
  730. * @return {void}
  731. */
  732. Subscriber.prototype.next = function (value) {
  733. if (!this.isStopped) {
  734. this._next(value);
  735. }
  736. };
  737. /**
  738. * The {@link Observer} callback to receive notifications of type `error` from
  739. * the Observable, with an attached {@link Error}. Notifies the Observer that
  740. * the Observable has experienced an error condition.
  741. * @param {any} [err] The `error` exception.
  742. * @return {void}
  743. */
  744. Subscriber.prototype.error = function (err) {
  745. if (!this.isStopped) {
  746. this.isStopped = true;
  747. this._error(err);
  748. }
  749. };
  750. /**
  751. * The {@link Observer} callback to receive a valueless notification of type
  752. * `complete` from the Observable. Notifies the Observer that the Observable
  753. * has finished sending push-based notifications.
  754. * @return {void}
  755. */
  756. Subscriber.prototype.complete = function () {
  757. if (!this.isStopped) {
  758. this.isStopped = true;
  759. this._complete();
  760. }
  761. };
  762. Subscriber.prototype.unsubscribe = function () {
  763. if (this.closed) {
  764. return;
  765. }
  766. this.isStopped = true;
  767. _super.prototype.unsubscribe.call(this);
  768. };
  769. Subscriber.prototype._next = function (value) {
  770. this.destination.next(value);
  771. };
  772. Subscriber.prototype._error = function (err) {
  773. this.destination.error(err);
  774. this.unsubscribe();
  775. };
  776. Subscriber.prototype._complete = function () {
  777. this.destination.complete();
  778. this.unsubscribe();
  779. };
  780. /** @deprecated internal use only */ Subscriber.prototype._unsubscribeAndRecycle = function () {
  781. var _a = this, _parent = _a._parent, _parents = _a._parents;
  782. this._parent = null;
  783. this._parents = null;
  784. this.unsubscribe();
  785. this.closed = false;
  786. this.isStopped = false;
  787. this._parent = _parent;
  788. this._parents = _parents;
  789. return this;
  790. };
  791. return Subscriber;
  792. }(Subscription));
  793. /**
  794. * We need this JSDoc comment for affecting ESDoc.
  795. * @ignore
  796. * @extends {Ignored}
  797. */
  798. var SafeSubscriber = (function (_super) {
  799. __extends(SafeSubscriber, _super);
  800. function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
  801. _super.call(this);
  802. this._parentSubscriber = _parentSubscriber;
  803. var next;
  804. var context = this;
  805. if (isFunction(observerOrNext)) {
  806. next = observerOrNext;
  807. }
  808. else if (observerOrNext) {
  809. next = observerOrNext.next;
  810. error = observerOrNext.error;
  811. complete = observerOrNext.complete;
  812. if (observerOrNext !== empty) {
  813. context = Object.create(observerOrNext);
  814. if (isFunction(context.unsubscribe)) {
  815. this.add(context.unsubscribe.bind(context));
  816. }
  817. context.unsubscribe = this.unsubscribe.bind(this);
  818. }
  819. }
  820. this._context = context;
  821. this._next = next;
  822. this._error = error;
  823. this._complete = complete;
  824. }
  825. SafeSubscriber.prototype.next = function (value) {
  826. if (!this.isStopped && this._next) {
  827. var _parentSubscriber = this._parentSubscriber;
  828. if (!_parentSubscriber.syncErrorThrowable) {
  829. this.__tryOrUnsub(this._next, value);
  830. }
  831. else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
  832. this.unsubscribe();
  833. }
  834. }
  835. };
  836. SafeSubscriber.prototype.error = function (err) {
  837. if (!this.isStopped) {
  838. var _parentSubscriber = this._parentSubscriber;
  839. if (this._error) {
  840. if (!_parentSubscriber.syncErrorThrowable) {
  841. this.__tryOrUnsub(this._error, err);
  842. this.unsubscribe();
  843. }
  844. else {
  845. this.__tryOrSetError(_parentSubscriber, this._error, err);
  846. this.unsubscribe();
  847. }
  848. }
  849. else if (!_parentSubscriber.syncErrorThrowable) {
  850. this.unsubscribe();
  851. throw err;
  852. }
  853. else {
  854. _parentSubscriber.syncErrorValue = err;
  855. _parentSubscriber.syncErrorThrown = true;
  856. this.unsubscribe();
  857. }
  858. }
  859. };
  860. SafeSubscriber.prototype.complete = function () {
  861. var _this = this;
  862. if (!this.isStopped) {
  863. var _parentSubscriber = this._parentSubscriber;
  864. if (this._complete) {
  865. var wrappedComplete = function () { return _this._complete.call(_this._context); };
  866. if (!_parentSubscriber.syncErrorThrowable) {
  867. this.__tryOrUnsub(wrappedComplete);
  868. this.unsubscribe();
  869. }
  870. else {
  871. this.__tryOrSetError(_parentSubscriber, wrappedComplete);
  872. this.unsubscribe();
  873. }
  874. }
  875. else {
  876. this.unsubscribe();
  877. }
  878. }
  879. };
  880. SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
  881. try {
  882. fn.call(this._context, value);
  883. }
  884. catch (err) {
  885. this.unsubscribe();
  886. throw err;
  887. }
  888. };
  889. SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
  890. try {
  891. fn.call(this._context, value);
  892. }
  893. catch (err) {
  894. parent.syncErrorValue = err;
  895. parent.syncErrorThrown = true;
  896. return true;
  897. }
  898. return false;
  899. };
  900. /** @deprecated internal use only */ SafeSubscriber.prototype._unsubscribe = function () {
  901. var _parentSubscriber = this._parentSubscriber;
  902. this._context = null;
  903. this._parentSubscriber = null;
  904. _parentSubscriber.unsubscribe();
  905. };
  906. return SafeSubscriber;
  907. }(Subscriber));
  908. function isTrustedSubscriber(obj) {
  909. return obj instanceof Subscriber || ('syncErrorThrowable' in obj && obj[rxSubscriber]);
  910. }
  911. function toSubscriber(nextOrObserver, error, complete) {
  912. if (nextOrObserver) {
  913. if (nextOrObserver instanceof Subscriber) {
  914. return nextOrObserver;
  915. }
  916. if (nextOrObserver[rxSubscriber]) {
  917. return nextOrObserver[rxSubscriber]();
  918. }
  919. }
  920. if (!nextOrObserver && !error && !complete) {
  921. return new Subscriber(empty);
  922. }
  923. return new Subscriber(nextOrObserver, error, complete);
  924. }
  925. function getSymbolObservable(context) {
  926. var $$observable;
  927. var Symbol = context.Symbol;
  928. if (typeof Symbol === 'function') {
  929. if (Symbol.observable) {
  930. $$observable = Symbol.observable;
  931. }
  932. else {
  933. $$observable = Symbol('observable');
  934. Symbol.observable = $$observable;
  935. }
  936. }
  937. else {
  938. $$observable = '@@observable';
  939. }
  940. return $$observable;
  941. }
  942. var observable = getSymbolObservable(_root);
  943. /**
  944. * @deprecated use observable instead
  945. */
  946. /* tslint:disable:no-empty */
  947. function noop() { }
  948. /* tslint:enable:max-line-length */
  949. function pipe() {
  950. var fns = [];
  951. for (var _i = 0; _i < arguments.length; _i++) {
  952. fns[_i - 0] = arguments[_i];
  953. }
  954. return pipeFromArray(fns);
  955. }
  956. /* @internal */
  957. function pipeFromArray(fns) {
  958. if (!fns) {
  959. return noop;
  960. }
  961. if (fns.length === 1) {
  962. return fns[0];
  963. }
  964. return function piped(input) {
  965. return fns.reduce(function (prev, fn) { return fn(prev); }, input);
  966. };
  967. }
  968. /**
  969. * A representation of any set of values over any amount of time. This is the most basic building block
  970. * of RxJS.
  971. *
  972. * @class Observable<T>
  973. */
  974. var Observable = (function () {
  975. /**
  976. * @constructor
  977. * @param {Function} subscribe the function that is called when the Observable is
  978. * initially subscribed to. This function is given a Subscriber, to which new values
  979. * can be `next`ed, or an `error` method can be called to raise an error, or
  980. * `complete` can be called to notify of a successful completion.
  981. */
  982. function Observable(subscribe) {
  983. this._isScalar = false;
  984. if (subscribe) {
  985. this._subscribe = subscribe;
  986. }
  987. }
  988. /**
  989. * Creates a new Observable, with this Observable as the source, and the passed
  990. * operator defined as the new observable's operator.
  991. * @method lift
  992. * @param {Operator} operator the operator defining the operation to take on the observable
  993. * @return {Observable} a new observable with the Operator applied
  994. */
  995. Observable.prototype.lift = function (operator) {
  996. var observable$$1 = new Observable();
  997. observable$$1.source = this;
  998. observable$$1.operator = operator;
  999. return observable$$1;
  1000. };
  1001. /**
  1002. * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
  1003. *
  1004. * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
  1005. *
  1006. * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
  1007. * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
  1008. * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
  1009. * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
  1010. * thought.
  1011. *
  1012. * Apart from starting the execution of an Observable, this method allows you to listen for values
  1013. * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
  1014. * following ways.
  1015. *
  1016. * The first way is creating an object that implements {@link Observer} interface. It should have methods
  1017. * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
  1018. * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
  1019. * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
  1020. * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
  1021. * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
  1022. * be left uncaught.
  1023. *
  1024. * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
  1025. * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
  1026. * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
  1027. * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
  1028. * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
  1029. * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
  1030. *
  1031. * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
  1032. * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
  1033. * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
  1034. * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
  1035. *
  1036. * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
  1037. * It is an Observable itself that decides when these functions will be called. For example {@link of}
  1038. * by default emits all its values synchronously. Always check documentation for how given Observable
  1039. * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
  1040. *
  1041. * @example <caption>Subscribe with an Observer</caption>
  1042. * const sumObserver = {
  1043. * sum: 0,
  1044. * next(value) {
  1045. * console.log('Adding: ' + value);
  1046. * this.sum = this.sum + value;
  1047. * },
  1048. * error() { // We actually could just remove this method,
  1049. * }, // since we do not really care about errors right now.
  1050. * complete() {
  1051. * console.log('Sum equals: ' + this.sum);
  1052. * }
  1053. * };
  1054. *
  1055. * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
  1056. * .subscribe(sumObserver);
  1057. *
  1058. * // Logs:
  1059. * // "Adding: 1"
  1060. * // "Adding: 2"
  1061. * // "Adding: 3"
  1062. * // "Sum equals: 6"
  1063. *
  1064. *
  1065. * @example <caption>Subscribe with functions</caption>
  1066. * let sum = 0;
  1067. *
  1068. * Rx.Observable.of(1, 2, 3)
  1069. * .subscribe(
  1070. * function(value) {
  1071. * console.log('Adding: ' + value);
  1072. * sum = sum + value;
  1073. * },
  1074. * undefined,
  1075. * function() {
  1076. * console.log('Sum equals: ' + sum);
  1077. * }
  1078. * );
  1079. *
  1080. * // Logs:
  1081. * // "Adding: 1"
  1082. * // "Adding: 2"
  1083. * // "Adding: 3"
  1084. * // "Sum equals: 6"
  1085. *
  1086. *
  1087. * @example <caption>Cancel a subscription</caption>
  1088. * const subscription = Rx.Observable.interval(1000).subscribe(
  1089. * num => console.log(num),
  1090. * undefined,
  1091. * () => console.log('completed!') // Will not be called, even
  1092. * ); // when cancelling subscription
  1093. *
  1094. *
  1095. * setTimeout(() => {
  1096. * subscription.unsubscribe();
  1097. * console.log('unsubscribed!');
  1098. * }, 2500);
  1099. *
  1100. * // Logs:
  1101. * // 0 after 1s
  1102. * // 1 after 2s
  1103. * // "unsubscribed!" after 2.5s
  1104. *
  1105. *
  1106. * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
  1107. * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
  1108. * Observable.
  1109. * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
  1110. * the error will be thrown as unhandled.
  1111. * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
  1112. * @return {ISubscription} a subscription reference to the registered handlers
  1113. * @method subscribe
  1114. */
  1115. Observable.prototype.subscribe = function (observerOrNext, error, complete) {
  1116. var operator = this.operator;
  1117. var sink = toSubscriber(observerOrNext, error, complete);
  1118. if (operator) {
  1119. operator.call(sink, this.source);
  1120. }
  1121. else {
  1122. sink.add(this.source || !sink.syncErrorThrowable ? this._subscribe(sink) : this._trySubscribe(sink));
  1123. }
  1124. if (sink.syncErrorThrowable) {
  1125. sink.syncErrorThrowable = false;
  1126. if (sink.syncErrorThrown) {
  1127. throw sink.syncErrorValue;
  1128. }
  1129. }
  1130. return sink;
  1131. };
  1132. Observable.prototype._trySubscribe = function (sink) {
  1133. try {
  1134. return this._subscribe(sink);
  1135. }
  1136. catch (err) {
  1137. sink.syncErrorThrown = true;
  1138. sink.syncErrorValue = err;
  1139. sink.error(err);
  1140. }
  1141. };
  1142. /**
  1143. * @method forEach
  1144. * @param {Function} next a handler for each value emitted by the observable
  1145. * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
  1146. * @return {Promise} a promise that either resolves on observable completion or
  1147. * rejects with the handled error
  1148. */
  1149. Observable.prototype.forEach = function (next, PromiseCtor) {
  1150. var _this = this;
  1151. if (!PromiseCtor) {
  1152. if (_root.Rx && _root.Rx.config && _root.Rx.config.Promise) {
  1153. PromiseCtor = _root.Rx.config.Promise;
  1154. }
  1155. else if (_root.Promise) {
  1156. PromiseCtor = _root.Promise;
  1157. }
  1158. }
  1159. if (!PromiseCtor) {
  1160. throw new Error('no Promise impl found');
  1161. }
  1162. return new PromiseCtor(function (resolve, reject) {
  1163. // Must be declared in a separate statement to avoid a RefernceError when
  1164. // accessing subscription below in the closure due to Temporal Dead Zone.
  1165. var subscription;
  1166. subscription = _this.subscribe(function (value) {
  1167. if (subscription) {
  1168. // if there is a subscription, then we can surmise
  1169. // the next handling is asynchronous. Any errors thrown
  1170. // need to be rejected explicitly and unsubscribe must be
  1171. // called manually
  1172. try {
  1173. next(value);
  1174. }
  1175. catch (err) {
  1176. reject(err);
  1177. subscription.unsubscribe();
  1178. }
  1179. }
  1180. else {
  1181. // if there is NO subscription, then we're getting a nexted
  1182. // value synchronously during subscription. We can just call it.
  1183. // If it errors, Observable's `subscribe` will ensure the
  1184. // unsubscription logic is called, then synchronously rethrow the error.
  1185. // After that, Promise will trap the error and send it
  1186. // down the rejection path.
  1187. next(value);
  1188. }
  1189. }, reject, resolve);
  1190. });
  1191. };
  1192. /** @deprecated internal use only */ Observable.prototype._subscribe = function (subscriber) {
  1193. return this.source.subscribe(subscriber);
  1194. };
  1195. /**
  1196. * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
  1197. * @method Symbol.observable
  1198. * @return {Observable} this instance of the observable
  1199. */
  1200. Observable.prototype[observable] = function () {
  1201. return this;
  1202. };
  1203. /* tslint:enable:max-line-length */
  1204. /**
  1205. * Used to stitch together functional operators into a chain.
  1206. * @method pipe
  1207. * @return {Observable} the Observable result of all of the operators having
  1208. * been called in the order they were passed in.
  1209. *
  1210. * @example
  1211. *
  1212. * import { map, filter, scan } from 'rxjs/operators';
  1213. *
  1214. * Rx.Observable.interval(1000)
  1215. * .pipe(
  1216. * filter(x => x % 2 === 0),
  1217. * map(x => x + x),
  1218. * scan((acc, x) => acc + x)
  1219. * )
  1220. * .subscribe(x => console.log(x))
  1221. */
  1222. Observable.prototype.pipe = function () {
  1223. var operations = [];
  1224. for (var _i = 0; _i < arguments.length; _i++) {
  1225. operations[_i - 0] = arguments[_i];
  1226. }
  1227. if (operations.length === 0) {
  1228. return this;
  1229. }
  1230. return pipeFromArray(operations)(this);
  1231. };
  1232. /* tslint:enable:max-line-length */
  1233. Observable.prototype.toPromise = function (PromiseCtor) {
  1234. var _this = this;
  1235. if (!PromiseCtor) {
  1236. if (_root.Rx && _root.Rx.config && _root.Rx.config.Promise) {
  1237. PromiseCtor = _root.Rx.config.Promise;
  1238. }
  1239. else if (_root.Promise) {
  1240. PromiseCtor = _root.Promise;
  1241. }
  1242. }
  1243. if (!PromiseCtor) {
  1244. throw new Error('no Promise impl found');
  1245. }
  1246. return new PromiseCtor(function (resolve, reject) {
  1247. var value;
  1248. _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
  1249. });
  1250. };
  1251. // HACK: Since TypeScript inherits static properties too, we have to
  1252. // fight against TypeScript here so Subject can have a different static create signature
  1253. /**
  1254. * Creates a new cold Observable by calling the Observable constructor
  1255. * @static true
  1256. * @owner Observable
  1257. * @method create
  1258. * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
  1259. * @return {Observable} a new cold observable
  1260. */
  1261. Observable.create = function (subscribe) {
  1262. return new Observable(subscribe);
  1263. };
  1264. return Observable;
  1265. }());
  1266. /**
  1267. * An error thrown when an action is invalid because the object has been
  1268. * unsubscribed.
  1269. *
  1270. * @see {@link Subject}
  1271. * @see {@link BehaviorSubject}
  1272. *
  1273. * @class ObjectUnsubscribedError
  1274. */
  1275. var ObjectUnsubscribedError = (function (_super) {
  1276. __extends(ObjectUnsubscribedError, _super);
  1277. function ObjectUnsubscribedError() {
  1278. var err = _super.call(this, 'object unsubscribed');
  1279. this.name = err.name = 'ObjectUnsubscribedError';
  1280. this.stack = err.stack;
  1281. this.message = err.message;
  1282. }
  1283. return ObjectUnsubscribedError;
  1284. }(Error));
  1285. /**
  1286. * We need this JSDoc comment for affecting ESDoc.
  1287. * @ignore
  1288. * @extends {Ignored}
  1289. */
  1290. var SubjectSubscription = (function (_super) {
  1291. __extends(SubjectSubscription, _super);
  1292. function SubjectSubscription(subject, subscriber) {
  1293. _super.call(this);
  1294. this.subject = subject;
  1295. this.subscriber = subscriber;
  1296. this.closed = false;
  1297. }
  1298. SubjectSubscription.prototype.unsubscribe = function () {
  1299. if (this.closed) {
  1300. return;
  1301. }
  1302. this.closed = true;
  1303. var subject = this.subject;
  1304. var observers = subject.observers;
  1305. this.subject = null;
  1306. if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
  1307. return;
  1308. }
  1309. var subscriberIndex = observers.indexOf(this.subscriber);
  1310. if (subscriberIndex !== -1) {
  1311. observers.splice(subscriberIndex, 1);
  1312. }
  1313. };
  1314. return SubjectSubscription;
  1315. }(Subscription));
  1316. /**
  1317. * @class SubjectSubscriber<T>
  1318. */
  1319. var SubjectSubscriber = (function (_super) {
  1320. __extends(SubjectSubscriber, _super);
  1321. function SubjectSubscriber(destination) {
  1322. _super.call(this, destination);
  1323. this.destination = destination;
  1324. }
  1325. return SubjectSubscriber;
  1326. }(Subscriber));
  1327. /**
  1328. * @class Subject<T>
  1329. */
  1330. var Subject = (function (_super) {
  1331. __extends(Subject, _super);
  1332. function Subject() {
  1333. _super.call(this);
  1334. this.observers = [];
  1335. this.closed = false;
  1336. this.isStopped = false;
  1337. this.hasError = false;
  1338. this.thrownError = null;
  1339. }
  1340. Subject.prototype[rxSubscriber] = function () {
  1341. return new SubjectSubscriber(this);
  1342. };
  1343. Subject.prototype.lift = function (operator) {
  1344. var subject = new AnonymousSubject(this, this);
  1345. subject.operator = operator;
  1346. return subject;
  1347. };
  1348. Subject.prototype.next = function (value) {
  1349. if (this.closed) {
  1350. throw new ObjectUnsubscribedError();
  1351. }
  1352. if (!this.isStopped) {
  1353. var observers = this.observers;
  1354. var len = observers.length;
  1355. var copy = observers.slice();
  1356. for (var i = 0; i < len; i++) {
  1357. copy[i].next(value);
  1358. }
  1359. }
  1360. };
  1361. Subject.prototype.error = function (err) {
  1362. if (this.closed) {
  1363. throw new ObjectUnsubscribedError();
  1364. }
  1365. this.hasError = true;
  1366. this.thrownError = err;
  1367. this.isStopped = true;
  1368. var observers = this.observers;
  1369. var len = observers.length;
  1370. var copy = observers.slice();
  1371. for (var i = 0; i < len; i++) {
  1372. copy[i].error(err);
  1373. }
  1374. this.observers.length = 0;
  1375. };
  1376. Subject.prototype.complete = function () {
  1377. if (this.closed) {
  1378. throw new ObjectUnsubscribedError();
  1379. }
  1380. this.isStopped = true;
  1381. var observers = this.observers;
  1382. var len = observers.length;
  1383. var copy = observers.slice();
  1384. for (var i = 0; i < len; i++) {
  1385. copy[i].complete();
  1386. }
  1387. this.observers.length = 0;
  1388. };
  1389. Subject.prototype.unsubscribe = function () {
  1390. this.isStopped = true;
  1391. this.closed = true;
  1392. this.observers = null;
  1393. };
  1394. Subject.prototype._trySubscribe = function (subscriber) {
  1395. if (this.closed) {
  1396. throw new ObjectUnsubscribedError();
  1397. }
  1398. else {
  1399. return _super.prototype._trySubscribe.call(this, subscriber);
  1400. }
  1401. };
  1402. /** @deprecated internal use only */ Subject.prototype._subscribe = function (subscriber) {
  1403. if (this.closed) {
  1404. throw new ObjectUnsubscribedError();
  1405. }
  1406. else if (this.hasError) {
  1407. subscriber.error(this.thrownError);
  1408. return Subscription.EMPTY;
  1409. }
  1410. else if (this.isStopped) {
  1411. subscriber.complete();
  1412. return Subscription.EMPTY;
  1413. }
  1414. else {
  1415. this.observers.push(subscriber);
  1416. return new SubjectSubscription(this, subscriber);
  1417. }
  1418. };
  1419. Subject.prototype.asObservable = function () {
  1420. var observable = new Observable();
  1421. observable.source = this;
  1422. return observable;
  1423. };
  1424. Subject.create = function (destination, source) {
  1425. return new AnonymousSubject(destination, source);
  1426. };
  1427. return Subject;
  1428. }(Observable));
  1429. /**
  1430. * @class AnonymousSubject<T>
  1431. */
  1432. var AnonymousSubject = (function (_super) {
  1433. __extends(AnonymousSubject, _super);
  1434. function AnonymousSubject(destination, source) {
  1435. _super.call(this);
  1436. this.destination = destination;
  1437. this.source = source;
  1438. }
  1439. AnonymousSubject.prototype.next = function (value) {
  1440. var destination = this.destination;
  1441. if (destination && destination.next) {
  1442. destination.next(value);
  1443. }
  1444. };
  1445. AnonymousSubject.prototype.error = function (err) {
  1446. var destination = this.destination;
  1447. if (destination && destination.error) {
  1448. this.destination.error(err);
  1449. }
  1450. };
  1451. AnonymousSubject.prototype.complete = function () {
  1452. var destination = this.destination;
  1453. if (destination && destination.complete) {
  1454. this.destination.complete();
  1455. }
  1456. };
  1457. /** @deprecated internal use only */ AnonymousSubject.prototype._subscribe = function (subscriber) {
  1458. var source = this.source;
  1459. if (source) {
  1460. return this.source.subscribe(subscriber);
  1461. }
  1462. else {
  1463. return Subscription.EMPTY;
  1464. }
  1465. };
  1466. return AnonymousSubject;
  1467. }(Subject));
  1468. /**
  1469. * @class AsyncSubject<T>
  1470. */
  1471. var AsyncSubject = (function (_super) {
  1472. __extends(AsyncSubject, _super);
  1473. function AsyncSubject() {
  1474. _super.apply(this, arguments);
  1475. this.value = null;
  1476. this.hasNext = false;
  1477. this.hasCompleted = false;
  1478. }
  1479. /** @deprecated internal use only */ AsyncSubject.prototype._subscribe = function (subscriber) {
  1480. if (this.hasError) {
  1481. subscriber.error(this.thrownError);
  1482. return Subscription.EMPTY;
  1483. }
  1484. else if (this.hasCompleted && this.hasNext) {
  1485. subscriber.next(this.value);
  1486. subscriber.complete();
  1487. return Subscription.EMPTY;
  1488. }
  1489. return _super.prototype._subscribe.call(this, subscriber);
  1490. };
  1491. AsyncSubject.prototype.next = function (value) {
  1492. if (!this.hasCompleted) {
  1493. this.value = value;
  1494. this.hasNext = true;
  1495. }
  1496. };
  1497. AsyncSubject.prototype.error = function (error) {
  1498. if (!this.hasCompleted) {
  1499. _super.prototype.error.call(this, error);
  1500. }
  1501. };
  1502. AsyncSubject.prototype.complete = function () {
  1503. this.hasCompleted = true;
  1504. if (this.hasNext) {
  1505. _super.prototype.next.call(this, this.value);
  1506. }
  1507. _super.prototype.complete.call(this);
  1508. };
  1509. return AsyncSubject;
  1510. }(Subject));
  1511. /**
  1512. * We need this JSDoc comment for affecting ESDoc.
  1513. * @extends {Ignored}
  1514. * @hide true
  1515. */
  1516. var BoundCallbackObservable = (function (_super) {
  1517. __extends(BoundCallbackObservable, _super);
  1518. function BoundCallbackObservable(callbackFunc, selector, args, context, scheduler) {
  1519. _super.call(this);
  1520. this.callbackFunc = callbackFunc;
  1521. this.selector = selector;
  1522. this.args = args;
  1523. this.context = context;
  1524. this.scheduler = scheduler;
  1525. }
  1526. /* tslint:enable:max-line-length */
  1527. /**
  1528. * Converts a callback API to a function that returns an Observable.
  1529. *
  1530. * <span class="informal">Give it a function `f` of type `f(x, callback)` and
  1531. * it will return a function `g` that when called as `g(x)` will output an
  1532. * Observable.</span>
  1533. *
  1534. * `bindCallback` is not an operator because its input and output are not
  1535. * Observables. The input is a function `func` with some parameters, the
  1536. * last parameter must be a callback function that `func` calls when it is
  1537. * done.
  1538. *
  1539. * The output of `bindCallback` is a function that takes the same parameters
  1540. * as `func`, except the last one (the callback). When the output function
  1541. * is called with arguments it will return an Observable. If function `func`
  1542. * calls its callback with one argument the Observable will emit that value.
  1543. * If on the other hand the callback is called with multiple values the resulting
  1544. * Observable will emit an array with said values as arguments.
  1545. *
  1546. * It is very important to remember that input function `func` is not called
  1547. * when the output function is, but rather when the Observable returned by the output
  1548. * function is subscribed. This means if `func` makes an AJAX request, that request
  1549. * will be made every time someone subscribes to the resulting Observable, but not before.
  1550. *
  1551. * Optionally, a selector function can be passed to `bindObservable`. The selector function
  1552. * takes the same arguments as the callback and returns the value that will be emitted by the Observable.
  1553. * Even though by default multiple arguments passed to callback appear in the stream as an array
  1554. * the selector function will be called with arguments directly, just as the callback would.
  1555. * This means you can imagine the default selector (when one is not provided explicitly)
  1556. * as a function that aggregates all its arguments into an array, or simply returns first argument
  1557. * if there is only one.
  1558. *
  1559. * The last optional parameter - {@link Scheduler} - can be used to control when the call
  1560. * to `func` happens after someone subscribes to Observable, as well as when results
  1561. * passed to callback will be emitted. By default, the subscription to an Observable calls `func`
  1562. * synchronously, but using `Scheduler.async` as the last parameter will defer the call to `func`,
  1563. * just like wrapping the call in `setTimeout` with a timeout of `0` would. If you use the async Scheduler
  1564. * and call `subscribe` on the output Observable all function calls that are currently executing
  1565. * will end before `func` is invoked.
  1566. *
  1567. * By default results passed to the callback are emitted immediately after `func` invokes the callback.
  1568. * In particular, if the callback is called synchronously the subscription of the resulting Observable
  1569. * will call the `next` function synchronously as well. If you want to defer that call,
  1570. * you may use `Scheduler.async` just as before. This means that by using `Scheduler.async` you can
  1571. * ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.
  1572. *
  1573. * Note that the Observable created by the output function will always emit a single value
  1574. * and then complete immediately. If `func` calls the callback multiple times, values from subsequent
  1575. * calls will not appear in the stream. If you need to listen for multiple calls,
  1576. * you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.
  1577. *
  1578. * If `func` depends on some context (`this` property) and is not already bound the context of `func`
  1579. * will be the context that the output function has at call time. In particular, if `func`
  1580. * is called as a method of some objec and if `func` is not already bound, in order to preserve the context
  1581. * it is recommended that the context of the output function is set to that object as well.
  1582. *
  1583. * If the input function calls its callback in the "node style" (i.e. first argument to callback is
  1584. * optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}
  1585. * provides convenient error handling and probably is a better choice.
  1586. * `bindCallback` will treat such functions the same as any other and error parameters
  1587. * (whether passed or not) will always be interpreted as regular callback argument.
  1588. *
  1589. *
  1590. * @example <caption>Convert jQuery's getJSON to an Observable API</caption>
  1591. * // Suppose we have jQuery.getJSON('/my/url', callback)
  1592. * var getJSONAsObservable = Rx.Observable.bindCallback(jQuery.getJSON);
  1593. * var result = getJSONAsObservable('/my/url');
  1594. * result.subscribe(x => console.log(x), e => console.error(e));
  1595. *
  1596. *
  1597. * @example <caption>Receive an array of arguments passed to a callback</caption>
  1598. * someFunction((a, b, c) => {
  1599. * console.log(a); // 5
  1600. * console.log(b); // 'some string'
  1601. * console.log(c); // {someProperty: 'someValue'}
  1602. * });
  1603. *
  1604. * const boundSomeFunction = Rx.Observable.bindCallback(someFunction);
  1605. * boundSomeFunction().subscribe(values => {
  1606. * console.log(values) // [5, 'some string', {someProperty: 'someValue'}]
  1607. * });
  1608. *
  1609. *
  1610. * @example <caption>Use bindCallback with a selector function</caption>
  1611. * someFunction((a, b, c) => {
  1612. * console.log(a); // 'a'
  1613. * console.log(b); // 'b'
  1614. * console.log(c); // 'c'
  1615. * });
  1616. *
  1617. * const boundSomeFunction = Rx.Observable.bindCallback(someFunction, (a, b, c) => a + b + c);
  1618. * boundSomeFunction().subscribe(value => {
  1619. * console.log(value) // 'abc'
  1620. * });
  1621. *
  1622. *
  1623. * @example <caption>Compare behaviour with and without async Scheduler</caption>
  1624. * function iCallMyCallbackSynchronously(cb) {
  1625. * cb();
  1626. * }
  1627. *
  1628. * const boundSyncFn = Rx.Observable.bindCallback(iCallMyCallbackSynchronously);
  1629. * const boundAsyncFn = Rx.Observable.bindCallback(iCallMyCallbackSynchronously, null, Rx.Scheduler.async);
  1630. *
  1631. * boundSyncFn().subscribe(() => console.log('I was sync!'));
  1632. * boundAsyncFn().subscribe(() => console.log('I was async!'));
  1633. * console.log('This happened...');
  1634. *
  1635. * // Logs:
  1636. * // I was sync!
  1637. * // This happened...
  1638. * // I was async!
  1639. *
  1640. *
  1641. * @example <caption>Use bindCallback on an object method</caption>
  1642. * const boundMethod = Rx.Observable.bindCallback(someObject.methodWithCallback);
  1643. * boundMethod.call(someObject) // make sure methodWithCallback has access to someObject
  1644. * .subscribe(subscriber);
  1645. *
  1646. *
  1647. * @see {@link bindNodeCallback}
  1648. * @see {@link from}
  1649. * @see {@link fromPromise}
  1650. *
  1651. * @param {function} func A function with a callback as the last parameter.
  1652. * @param {function} [selector] A function which takes the arguments from the
  1653. * callback and maps them to a value that is emitted on the output Observable.
  1654. * @param {Scheduler} [scheduler] The scheduler on which to schedule the
  1655. * callbacks.
  1656. * @return {function(...params: *): Observable} A function which returns the
  1657. * Observable that delivers the same values the callback would deliver.
  1658. * @static true
  1659. * @name bindCallback
  1660. * @owner Observable
  1661. */
  1662. BoundCallbackObservable.create = function (func, selector, scheduler) {
  1663. if (selector === void 0) { selector = undefined; }
  1664. return function () {
  1665. var args = [];
  1666. for (var _i = 0; _i < arguments.length; _i++) {
  1667. args[_i - 0] = arguments[_i];
  1668. }
  1669. return new BoundCallbackObservable(func, selector, args, this, scheduler);
  1670. };
  1671. };
  1672. /** @deprecated internal use only */ BoundCallbackObservable.prototype._subscribe = function (subscriber) {
  1673. var callbackFunc = this.callbackFunc;
  1674. var args = this.args;
  1675. var scheduler = this.scheduler;
  1676. var subject = this.subject;
  1677. if (!scheduler) {
  1678. if (!subject) {
  1679. subject = this.subject = new AsyncSubject();
  1680. var handler = function handlerFn() {
  1681. var innerArgs = [];
  1682. for (var _i = 0; _i < arguments.length; _i++) {
  1683. innerArgs[_i - 0] = arguments[_i];
  1684. }
  1685. var source = handlerFn.source;
  1686. var selector = source.selector, subject = source.subject;
  1687. if (selector) {
  1688. var result_1 = tryCatch(selector).apply(this, innerArgs);
  1689. if (result_1 === errorObject) {
  1690. subject.error(errorObject.e);
  1691. }
  1692. else {
  1693. subject.next(result_1);
  1694. subject.complete();
  1695. }
  1696. }
  1697. else {
  1698. subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
  1699. subject.complete();
  1700. }
  1701. };
  1702. // use named function instance to avoid closure.
  1703. handler.source = this;
  1704. var result = tryCatch(callbackFunc).apply(this.context, args.concat(handler));
  1705. if (result === errorObject) {
  1706. subject.error(errorObject.e);
  1707. }
  1708. }
  1709. return subject.subscribe(subscriber);
  1710. }
  1711. else {
  1712. return scheduler.schedule(BoundCallbackObservable.dispatch, 0, { source: this, subscriber: subscriber, context: this.context });
  1713. }
  1714. };
  1715. BoundCallbackObservable.dispatch = function (state) {
  1716. var self = this;
  1717. var source = state.source, subscriber = state.subscriber, context = state.context;
  1718. var callbackFunc = source.callbackFunc, args = source.args, scheduler = source.scheduler;
  1719. var subject = source.subject;
  1720. if (!subject) {
  1721. subject = source.subject = new AsyncSubject();
  1722. var handler = function handlerFn() {
  1723. var innerArgs = [];
  1724. for (var _i = 0; _i < arguments.length; _i++) {
  1725. innerArgs[_i - 0] = arguments[_i];
  1726. }
  1727. var source = handlerFn.source;
  1728. var selector = source.selector, subject = source.subject;
  1729. if (selector) {
  1730. var result_2 = tryCatch(selector).apply(this, innerArgs);
  1731. if (result_2 === errorObject) {
  1732. self.add(scheduler.schedule(dispatchError, 0, { err: errorObject.e, subject: subject }));
  1733. }
  1734. else {
  1735. self.add(scheduler.schedule(dispatchNext, 0, { value: result_2, subject: subject }));
  1736. }
  1737. }
  1738. else {
  1739. var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
  1740. self.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
  1741. }
  1742. };
  1743. // use named function to pass values in without closure
  1744. handler.source = source;
  1745. var result = tryCatch(callbackFunc).apply(context, args.concat(handler));
  1746. if (result === errorObject) {
  1747. subject.error(errorObject.e);
  1748. }
  1749. }
  1750. self.add(subject.subscribe(subscriber));
  1751. };
  1752. return BoundCallbackObservable;
  1753. }(Observable));
  1754. function dispatchNext(arg) {
  1755. var value = arg.value, subject = arg.subject;
  1756. subject.next(value);
  1757. subject.complete();
  1758. }
  1759. function dispatchError(arg) {
  1760. var err = arg.err, subject = arg.subject;
  1761. subject.error(err);
  1762. }
  1763. var bindCallback = BoundCallbackObservable.create;
  1764. Observable.bindCallback = bindCallback;
  1765. /**
  1766. * We need this JSDoc comment for affecting ESDoc.
  1767. * @extends {Ignored}
  1768. * @hide true
  1769. */
  1770. var BoundNodeCallbackObservable = (function (_super) {
  1771. __extends(BoundNodeCallbackObservable, _super);
  1772. function BoundNodeCallbackObservable(callbackFunc, selector, args, context, scheduler) {
  1773. _super.call(this);
  1774. this.callbackFunc = callbackFunc;
  1775. this.selector = selector;
  1776. this.args = args;
  1777. this.context = context;
  1778. this.scheduler = scheduler;
  1779. }
  1780. /* tslint:enable:max-line-length */
  1781. /**
  1782. * Converts a Node.js-style callback API to a function that returns an
  1783. * Observable.
  1784. *
  1785. * <span class="informal">It's just like {@link bindCallback}, but the
  1786. * callback is expected to be of type `callback(error, result)`.</span>
  1787. *
  1788. * `bindNodeCallback` is not an operator because its input and output are not
  1789. * Observables. The input is a function `func` with some parameters, but the
  1790. * last parameter must be a callback function that `func` calls when it is
  1791. * done. The callback function is expected to follow Node.js conventions,
  1792. * where the first argument to the callback is an error object, signaling
  1793. * whether call was successful. If that object is passed to callback, it means
  1794. * something went wrong.
  1795. *
  1796. * The output of `bindNodeCallback` is a function that takes the same
  1797. * parameters as `func`, except the last one (the callback). When the output
  1798. * function is called with arguments, it will return an Observable.
  1799. * If `func` calls its callback with error parameter present, Observable will
  1800. * error with that value as well. If error parameter is not passed, Observable will emit
  1801. * second parameter. If there are more parameters (third and so on),
  1802. * Observable will emit an array with all arguments, except first error argument.
  1803. *
  1804. * Optionally `bindNodeCallback` accepts selector function, which allows you to
  1805. * make resulting Observable emit value computed by selector, instead of regular
  1806. * callback arguments. It works similarly to {@link bindCallback} selector, but
  1807. * Node.js-style error argument will never be passed to that function.
  1808. *
  1809. * Note that `func` will not be called at the same time output function is,
  1810. * but rather whenever resulting Observable is subscribed. By default call to
  1811. * `func` will happen synchronously after subscription, but that can be changed
  1812. * with proper {@link Scheduler} provided as optional third parameter. Scheduler
  1813. * can also control when values from callback will be emitted by Observable.
  1814. * To find out more, check out documentation for {@link bindCallback}, where
  1815. * Scheduler works exactly the same.
  1816. *
  1817. * As in {@link bindCallback}, context (`this` property) of input function will be set to context
  1818. * of returned function, when it is called.
  1819. *
  1820. * After Observable emits value, it will complete immediately. This means
  1821. * even if `func` calls callback again, values from second and consecutive
  1822. * calls will never appear on the stream. If you need to handle functions
  1823. * that call callbacks multiple times, check out {@link fromEvent} or
  1824. * {@link fromEventPattern} instead.
  1825. *
  1826. * Note that `bindNodeCallback` can be used in non-Node.js environments as well.
  1827. * "Node.js-style" callbacks are just a convention, so if you write for
  1828. * browsers or any other environment and API you use implements that callback style,
  1829. * `bindNodeCallback` can be safely used on that API functions as well.
  1830. *
  1831. * Remember that Error object passed to callback does not have to be an instance
  1832. * of JavaScript built-in `Error` object. In fact, it does not even have to an object.
  1833. * Error parameter of callback function is interpreted as "present", when value
  1834. * of that parameter is truthy. It could be, for example, non-zero number, non-empty
  1835. * string or boolean `true`. In all of these cases resulting Observable would error
  1836. * with that value. This means usually regular style callbacks will fail very often when
  1837. * `bindNodeCallback` is used. If your Observable errors much more often then you
  1838. * would expect, check if callback really is called in Node.js-style and, if not,
  1839. * switch to {@link bindCallback} instead.
  1840. *
  1841. * Note that even if error parameter is technically present in callback, but its value
  1842. * is falsy, it still won't appear in array emitted by Observable or in selector function.
  1843. *
  1844. *
  1845. * @example <caption>Read a file from the filesystem and get the data as an Observable</caption>
  1846. * import * as fs from 'fs';
  1847. * var readFileAsObservable = Rx.Observable.bindNodeCallback(fs.readFile);
  1848. * var result = readFileAsObservable('./roadNames.txt', 'utf8');
  1849. * result.subscribe(x => console.log(x), e => console.error(e));
  1850. *
  1851. *
  1852. * @example <caption>Use on function calling callback with multiple arguments</caption>
  1853. * someFunction((err, a, b) => {
  1854. * console.log(err); // null
  1855. * console.log(a); // 5
  1856. * console.log(b); // "some string"
  1857. * });
  1858. * var boundSomeFunction = Rx.Observable.bindNodeCallback(someFunction);
  1859. * boundSomeFunction()
  1860. * .subscribe(value => {
  1861. * console.log(value); // [5, "some string"]
  1862. * });
  1863. *
  1864. *
  1865. * @example <caption>Use with selector function</caption>
  1866. * someFunction((err, a, b) => {
  1867. * console.log(err); // undefined
  1868. * console.log(a); // "abc"
  1869. * console.log(b); // "DEF"
  1870. * });
  1871. * var boundSomeFunction = Rx.Observable.bindNodeCallback(someFunction, (a, b) => a + b);
  1872. * boundSomeFunction()
  1873. * .subscribe(value => {
  1874. * console.log(value); // "abcDEF"
  1875. * });
  1876. *
  1877. *
  1878. * @example <caption>Use on function calling callback in regular style</caption>
  1879. * someFunction(a => {
  1880. * console.log(a); // 5
  1881. * });
  1882. * var boundSomeFunction = Rx.Observable.bindNodeCallback(someFunction);
  1883. * boundSomeFunction()
  1884. * .subscribe(
  1885. * value => {} // never gets called
  1886. * err => console.log(err) // 5
  1887. *);
  1888. *
  1889. *
  1890. * @see {@link bindCallback}
  1891. * @see {@link from}
  1892. * @see {@link fromPromise}
  1893. *
  1894. * @param {function} func Function with a Node.js-style callback as the last parameter.
  1895. * @param {function} [selector] A function which takes the arguments from the
  1896. * callback and maps those to a value to emit on the output Observable.
  1897. * @param {Scheduler} [scheduler] The scheduler on which to schedule the
  1898. * callbacks.
  1899. * @return {function(...params: *): Observable} A function which returns the
  1900. * Observable that delivers the same values the Node.js callback would
  1901. * deliver.
  1902. * @static true
  1903. * @name bindNodeCallback
  1904. * @owner Observable
  1905. */
  1906. BoundNodeCallbackObservable.create = function (func, selector, scheduler) {
  1907. if (selector === void 0) { selector = undefined; }
  1908. return function () {
  1909. var args = [];
  1910. for (var _i = 0; _i < arguments.length; _i++) {
  1911. args[_i - 0] = arguments[_i];
  1912. }
  1913. return new BoundNodeCallbackObservable(func, selector, args, this, scheduler);
  1914. };
  1915. };
  1916. /** @deprecated internal use only */ BoundNodeCallbackObservable.prototype._subscribe = function (subscriber) {
  1917. var callbackFunc = this.callbackFunc;
  1918. var args = this.args;
  1919. var scheduler = this.scheduler;
  1920. var subject = this.subject;
  1921. if (!scheduler) {
  1922. if (!subject) {
  1923. subject = this.subject = new AsyncSubject();
  1924. var handler = function handlerFn() {
  1925. var innerArgs = [];
  1926. for (var _i = 0; _i < arguments.length; _i++) {
  1927. innerArgs[_i - 0] = arguments[_i];
  1928. }
  1929. var source = handlerFn.source;
  1930. var selector = source.selector, subject = source.subject;
  1931. var err = innerArgs.shift();
  1932. if (err) {
  1933. subject.error(err);
  1934. }
  1935. else if (selector) {
  1936. var result_1 = tryCatch(selector).apply(this, innerArgs);
  1937. if (result_1 === errorObject) {
  1938. subject.error(errorObject.e);
  1939. }
  1940. else {
  1941. subject.next(result_1);
  1942. subject.complete();
  1943. }
  1944. }
  1945. else {
  1946. subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
  1947. subject.complete();
  1948. }
  1949. };
  1950. // use named function instance to avoid closure.
  1951. handler.source = this;
  1952. var result = tryCatch(callbackFunc).apply(this.context, args.concat(handler));
  1953. if (result === errorObject) {
  1954. subject.error(errorObject.e);
  1955. }
  1956. }
  1957. return subject.subscribe(subscriber);
  1958. }
  1959. else {
  1960. return scheduler.schedule(dispatch, 0, { source: this, subscriber: subscriber, context: this.context });
  1961. }
  1962. };
  1963. return BoundNodeCallbackObservable;
  1964. }(Observable));
  1965. function dispatch(state) {
  1966. var self = this;
  1967. var source = state.source, subscriber = state.subscriber, context = state.context;
  1968. // XXX: cast to `any` to access to the private field in `source`.
  1969. var _a = source, callbackFunc = _a.callbackFunc, args = _a.args, scheduler = _a.scheduler;
  1970. var subject = source.subject;
  1971. if (!subject) {
  1972. subject = source.subject = new AsyncSubject();
  1973. var handler = function handlerFn() {
  1974. var innerArgs = [];
  1975. for (var _i = 0; _i < arguments.length; _i++) {
  1976. innerArgs[_i - 0] = arguments[_i];
  1977. }
  1978. var source = handlerFn.source;
  1979. var selector = source.selector, subject = source.subject;
  1980. var err = innerArgs.shift();
  1981. if (err) {
  1982. self.add(scheduler.schedule(dispatchError$1, 0, { err: err, subject: subject }));
  1983. }
  1984. else if (selector) {
  1985. var result_2 = tryCatch(selector).apply(this, innerArgs);
  1986. if (result_2 === errorObject) {
  1987. self.add(scheduler.schedule(dispatchError$1, 0, { err: errorObject.e, subject: subject }));
  1988. }
  1989. else {
  1990. self.add(scheduler.schedule(dispatchNext$1, 0, { value: result_2, subject: subject }));
  1991. }
  1992. }
  1993. else {
  1994. var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
  1995. self.add(scheduler.schedule(dispatchNext$1, 0, { value: value, subject: subject }));
  1996. }
  1997. };
  1998. // use named function to pass values in without closure
  1999. handler.source = source;
  2000. var result = tryCatch(callbackFunc).apply(context, args.concat(handler));
  2001. if (result === errorObject) {
  2002. self.add(scheduler.schedule(dispatchError$1, 0, { err: errorObject.e, subject: subject }));
  2003. }
  2004. }
  2005. self.add(subject.subscribe(subscriber));
  2006. }
  2007. function dispatchNext$1(arg) {
  2008. var value = arg.value, subject = arg.subject;
  2009. subject.next(value);
  2010. subject.complete();
  2011. }
  2012. function dispatchError$1(arg) {
  2013. var err = arg.err, subject = arg.subject;
  2014. subject.error(err);
  2015. }
  2016. var bindNodeCallback = BoundNodeCallbackObservable.create;
  2017. Observable.bindNodeCallback = bindNodeCallback;
  2018. function isScheduler(value) {
  2019. return value && typeof value.schedule === 'function';
  2020. }
  2021. /**
  2022. * We need this JSDoc comment for affecting ESDoc.
  2023. * @extends {Ignored}
  2024. * @hide true
  2025. */
  2026. var ScalarObservable = (function (_super) {
  2027. __extends(ScalarObservable, _super);
  2028. function ScalarObservable(value, scheduler) {
  2029. _super.call(this);
  2030. this.value = value;
  2031. this.scheduler = scheduler;
  2032. this._isScalar = true;
  2033. if (scheduler) {
  2034. this._isScalar = false;
  2035. }
  2036. }
  2037. ScalarObservable.create = function (value, scheduler) {
  2038. return new ScalarObservable(value, scheduler);
  2039. };
  2040. ScalarObservable.dispatch = function (state) {
  2041. var done = state.done, value = state.value, subscriber = state.subscriber;
  2042. if (done) {
  2043. subscriber.complete();
  2044. return;
  2045. }
  2046. subscriber.next(value);
  2047. if (subscriber.closed) {
  2048. return;
  2049. }
  2050. state.done = true;
  2051. this.schedule(state);
  2052. };
  2053. /** @deprecated internal use only */ ScalarObservable.prototype._subscribe = function (subscriber) {
  2054. var value = this.value;
  2055. var scheduler = this.scheduler;
  2056. if (scheduler) {
  2057. return scheduler.schedule(ScalarObservable.dispatch, 0, {
  2058. done: false, value: value, subscriber: subscriber
  2059. });
  2060. }
  2061. else {
  2062. subscriber.next(value);
  2063. if (!subscriber.closed) {
  2064. subscriber.complete();
  2065. }
  2066. }
  2067. };
  2068. return ScalarObservable;
  2069. }(Observable));
  2070. /**
  2071. * We need this JSDoc comment for affecting ESDoc.
  2072. * @extends {Ignored}
  2073. * @hide true
  2074. */
  2075. var EmptyObservable = (function (_super) {
  2076. __extends(EmptyObservable, _super);
  2077. function EmptyObservable(scheduler) {
  2078. _super.call(this);
  2079. this.scheduler = scheduler;
  2080. }
  2081. /**
  2082. * Creates an Observable that emits no items to the Observer and immediately
  2083. * emits a complete notification.
  2084. *
  2085. * <span class="informal">Just emits 'complete', and nothing else.
  2086. * </span>
  2087. *
  2088. * <img src="./img/empty.png" width="100%">
  2089. *
  2090. * This static operator is useful for creating a simple Observable that only
  2091. * emits the complete notification. It can be used for composing with other
  2092. * Observables, such as in a {@link mergeMap}.
  2093. *
  2094. * @example <caption>Emit the number 7, then complete.</caption>
  2095. * var result = Rx.Observable.empty().startWith(7);
  2096. * result.subscribe(x => console.log(x));
  2097. *
  2098. * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
  2099. * var interval = Rx.Observable.interval(1000);
  2100. * var result = interval.mergeMap(x =>
  2101. * x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
  2102. * );
  2103. * result.subscribe(x => console.log(x));
  2104. *
  2105. * // Results in the following to the console:
  2106. * // x is equal to the count on the interval eg(0,1,2,3,...)
  2107. * // x will occur every 1000ms
  2108. * // if x % 2 is equal to 1 print abc
  2109. * // if x % 2 is not equal to 1 nothing will be output
  2110. *
  2111. * @see {@link create}
  2112. * @see {@link never}
  2113. * @see {@link of}
  2114. * @see {@link throw}
  2115. *
  2116. * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
  2117. * the emission of the complete notification.
  2118. * @return {Observable} An "empty" Observable: emits only the complete
  2119. * notification.
  2120. * @static true
  2121. * @name empty
  2122. * @owner Observable
  2123. */
  2124. EmptyObservable.create = function (scheduler) {
  2125. return new EmptyObservable(scheduler);
  2126. };
  2127. EmptyObservable.dispatch = function (arg) {
  2128. var subscriber = arg.subscriber;
  2129. subscriber.complete();
  2130. };
  2131. /** @deprecated internal use only */ EmptyObservable.prototype._subscribe = function (subscriber) {
  2132. var scheduler = this.scheduler;
  2133. if (scheduler) {
  2134. return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
  2135. }
  2136. else {
  2137. subscriber.complete();
  2138. }
  2139. };
  2140. return EmptyObservable;
  2141. }(Observable));
  2142. /**
  2143. * We need this JSDoc comment for affecting ESDoc.
  2144. * @extends {Ignored}
  2145. * @hide true
  2146. */
  2147. var ArrayObservable = (function (_super) {
  2148. __extends(ArrayObservable, _super);
  2149. function ArrayObservable(array, scheduler) {
  2150. _super.call(this);
  2151. this.array = array;
  2152. this.scheduler = scheduler;
  2153. if (!scheduler && array.length === 1) {
  2154. this._isScalar = true;
  2155. this.value = array[0];
  2156. }
  2157. }
  2158. ArrayObservable.create = function (array, scheduler) {
  2159. return new ArrayObservable(array, scheduler);
  2160. };
  2161. /**
  2162. * Creates an Observable that emits some values you specify as arguments,
  2163. * immediately one after the other, and then emits a complete notification.
  2164. *
  2165. * <span class="informal">Emits the arguments you provide, then completes.
  2166. * </span>
  2167. *
  2168. * <img src="./img/of.png" width="100%">
  2169. *
  2170. * This static operator is useful for creating a simple Observable that only
  2171. * emits the arguments given, and the complete notification thereafter. It can
  2172. * be used for composing with other Observables, such as with {@link concat}.
  2173. * By default, it uses a `null` IScheduler, which means the `next`
  2174. * notifications are sent synchronously, although with a different IScheduler
  2175. * it is possible to determine when those notifications will be delivered.
  2176. *
  2177. * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
  2178. * var numbers = Rx.Observable.of(10, 20, 30);
  2179. * var letters = Rx.Observable.of('a', 'b', 'c');
  2180. * var interval = Rx.Observable.interval(1000);
  2181. * var result = numbers.concat(letters).concat(interval);
  2182. * result.subscribe(x => console.log(x));
  2183. *
  2184. * @see {@link create}
  2185. * @see {@link empty}
  2186. * @see {@link never}
  2187. * @see {@link throw}
  2188. *
  2189. * @param {...T} values Arguments that represent `next` values to be emitted.
  2190. * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
  2191. * the emissions of the `next` notifications.
  2192. * @return {Observable<T>} An Observable that emits each given input value.
  2193. * @static true
  2194. * @name of
  2195. * @owner Observable
  2196. */
  2197. ArrayObservable.of = function () {
  2198. var array = [];
  2199. for (var _i = 0; _i < arguments.length; _i++) {
  2200. array[_i - 0] = arguments[_i];
  2201. }
  2202. var scheduler = array[array.length - 1];
  2203. if (isScheduler(scheduler)) {
  2204. array.pop();
  2205. }
  2206. else {
  2207. scheduler = null;
  2208. }
  2209. var len = array.length;
  2210. if (len > 1) {
  2211. return new ArrayObservable(array, scheduler);
  2212. }
  2213. else if (len === 1) {
  2214. return new ScalarObservable(array[0], scheduler);
  2215. }
  2216. else {
  2217. return new EmptyObservable(scheduler);
  2218. }
  2219. };
  2220. ArrayObservable.dispatch = function (state) {
  2221. var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
  2222. if (index >= count) {
  2223. subscriber.complete();
  2224. return;
  2225. }
  2226. subscriber.next(array[index]);
  2227. if (subscriber.closed) {
  2228. return;
  2229. }
  2230. state.index = index + 1;
  2231. this.schedule(state);
  2232. };
  2233. /** @deprecated internal use only */ ArrayObservable.prototype._subscribe = function (subscriber) {
  2234. var index = 0;
  2235. var array = this.array;
  2236. var count = array.length;
  2237. var scheduler = this.scheduler;
  2238. if (scheduler) {
  2239. return scheduler.schedule(ArrayObservable.dispatch, 0, {
  2240. array: array, index: index, count: count, subscriber: subscriber
  2241. });
  2242. }
  2243. else {
  2244. for (var i = 0; i < count && !subscriber.closed; i++) {
  2245. subscriber.next(array[i]);
  2246. }
  2247. subscriber.complete();
  2248. }
  2249. };
  2250. return ArrayObservable;
  2251. }(Observable));
  2252. /**
  2253. * We need this JSDoc comment for affecting ESDoc.
  2254. * @ignore
  2255. * @extends {Ignored}
  2256. */
  2257. var OuterSubscriber = (function (_super) {
  2258. __extends(OuterSubscriber, _super);
  2259. function OuterSubscriber() {
  2260. _super.apply(this, arguments);
  2261. }
  2262. OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  2263. this.destination.next(innerValue);
  2264. };
  2265. OuterSubscriber.prototype.notifyError = function (error, innerSub) {
  2266. this.destination.error(error);
  2267. };
  2268. OuterSubscriber.prototype.notifyComplete = function (innerSub) {
  2269. this.destination.complete();
  2270. };
  2271. return OuterSubscriber;
  2272. }(Subscriber));
  2273. var isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
  2274. function isPromise(value) {
  2275. return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
  2276. }
  2277. function symbolIteratorPonyfill(root$$1) {
  2278. var Symbol = root$$1.Symbol;
  2279. if (typeof Symbol === 'function') {
  2280. if (!Symbol.iterator) {
  2281. Symbol.iterator = Symbol('iterator polyfill');
  2282. }
  2283. return Symbol.iterator;
  2284. }
  2285. else {
  2286. // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
  2287. var Set_1 = root$$1.Set;
  2288. if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
  2289. return '@@iterator';
  2290. }
  2291. var Map_1 = root$$1.Map;
  2292. // required for compatability with es6-shim
  2293. if (Map_1) {
  2294. var keys = Object.getOwnPropertyNames(Map_1.prototype);
  2295. for (var i = 0; i < keys.length; ++i) {
  2296. var key = keys[i];
  2297. // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
  2298. if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
  2299. return key;
  2300. }
  2301. }
  2302. }
  2303. return '@@iterator';
  2304. }
  2305. }
  2306. var iterator = symbolIteratorPonyfill(_root);
  2307. /**
  2308. * @deprecated use iterator instead
  2309. */
  2310. /**
  2311. * We need this JSDoc comment for affecting ESDoc.
  2312. * @ignore
  2313. * @extends {Ignored}
  2314. */
  2315. var InnerSubscriber = (function (_super) {
  2316. __extends(InnerSubscriber, _super);
  2317. function InnerSubscriber(parent, outerValue, outerIndex) {
  2318. _super.call(this);
  2319. this.parent = parent;
  2320. this.outerValue = outerValue;
  2321. this.outerIndex = outerIndex;
  2322. this.index = 0;
  2323. }
  2324. InnerSubscriber.prototype._next = function (value) {
  2325. this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
  2326. };
  2327. InnerSubscriber.prototype._error = function (error) {
  2328. this.parent.notifyError(error, this);
  2329. this.unsubscribe();
  2330. };
  2331. InnerSubscriber.prototype._complete = function () {
  2332. this.parent.notifyComplete(this);
  2333. this.unsubscribe();
  2334. };
  2335. return InnerSubscriber;
  2336. }(Subscriber));
  2337. function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
  2338. var destination = new InnerSubscriber(outerSubscriber, outerValue, outerIndex);
  2339. if (destination.closed) {
  2340. return null;
  2341. }
  2342. if (result instanceof Observable) {
  2343. if (result._isScalar) {
  2344. destination.next(result.value);
  2345. destination.complete();
  2346. return null;
  2347. }
  2348. else {
  2349. destination.syncErrorThrowable = true;
  2350. return result.subscribe(destination);
  2351. }
  2352. }
  2353. else if (isArrayLike(result)) {
  2354. for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
  2355. destination.next(result[i]);
  2356. }
  2357. if (!destination.closed) {
  2358. destination.complete();
  2359. }
  2360. }
  2361. else if (isPromise(result)) {
  2362. result.then(function (value) {
  2363. if (!destination.closed) {
  2364. destination.next(value);
  2365. destination.complete();
  2366. }
  2367. }, function (err) { return destination.error(err); })
  2368. .then(null, function (err) {
  2369. // Escaping the Promise trap: globally throw unhandled errors
  2370. _root.setTimeout(function () { throw err; });
  2371. });
  2372. return destination;
  2373. }
  2374. else if (result && typeof result[iterator] === 'function') {
  2375. var iterator$$1 = result[iterator]();
  2376. do {
  2377. var item = iterator$$1.next();
  2378. if (item.done) {
  2379. destination.complete();
  2380. break;
  2381. }
  2382. destination.next(item.value);
  2383. if (destination.closed) {
  2384. break;
  2385. }
  2386. } while (true);
  2387. }
  2388. else if (result && typeof result[observable] === 'function') {
  2389. var obs = result[observable]();
  2390. if (typeof obs.subscribe !== 'function') {
  2391. destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
  2392. }
  2393. else {
  2394. return obs.subscribe(new InnerSubscriber(outerSubscriber, outerValue, outerIndex));
  2395. }
  2396. }
  2397. else {
  2398. var value = isObject(result) ? 'an invalid object' : "'" + result + "'";
  2399. var msg = ("You provided " + value + " where a stream was expected.")
  2400. + ' You can provide an Observable, Promise, Array, or Iterable.';
  2401. destination.error(new TypeError(msg));
  2402. }
  2403. return null;
  2404. }
  2405. var none = {};
  2406. /* tslint:enable:max-line-length */
  2407. /**
  2408. * Combines multiple Observables to create an Observable whose values are
  2409. * calculated from the latest values of each of its input Observables.
  2410. *
  2411. * <span class="informal">Whenever any input Observable emits a value, it
  2412. * computes a formula using the latest values from all the inputs, then emits
  2413. * the output of that formula.</span>
  2414. *
  2415. * <img src="./img/combineLatest.png" width="100%">
  2416. *
  2417. * `combineLatest` combines the values from this Observable with values from
  2418. * Observables passed as arguments. This is done by subscribing to each
  2419. * Observable, in order, and collecting an array of each of the most recent
  2420. * values any time any of the input Observables emits, then either taking that
  2421. * array and passing it as arguments to an optional `project` function and
  2422. * emitting the return value of that, or just emitting the array of recent
  2423. * values directly if there is no `project` function.
  2424. *
  2425. * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
  2426. * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
  2427. * var height = Rx.Observable.of(1.76, 1.77, 1.78);
  2428. * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
  2429. * bmi.subscribe(x => console.log('BMI is ' + x));
  2430. *
  2431. * // With output to console:
  2432. * // BMI is 24.212293388429753
  2433. * // BMI is 23.93948099205209
  2434. * // BMI is 23.671253629592222
  2435. *
  2436. * @see {@link combineAll}
  2437. * @see {@link merge}
  2438. * @see {@link withLatestFrom}
  2439. *
  2440. * @param {ObservableInput} other An input Observable to combine with the source
  2441. * Observable. More than one input Observables may be given as argument.
  2442. * @param {function} [project] An optional function to project the values from
  2443. * the combined latest values into a new value on the output Observable.
  2444. * @return {Observable} An Observable of projected values from the most recent
  2445. * values from each input Observable, or an array of the most recent values from
  2446. * each input Observable.
  2447. * @method combineLatest
  2448. * @owner Observable
  2449. */
  2450. function combineLatest$1() {
  2451. var observables = [];
  2452. for (var _i = 0; _i < arguments.length; _i++) {
  2453. observables[_i - 0] = arguments[_i];
  2454. }
  2455. var project = null;
  2456. if (typeof observables[observables.length - 1] === 'function') {
  2457. project = observables.pop();
  2458. }
  2459. // if the first and only other argument besides the resultSelector is an array
  2460. // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
  2461. if (observables.length === 1 && isArray(observables[0])) {
  2462. observables = observables[0].slice();
  2463. }
  2464. return function (source) { return source.lift.call(new ArrayObservable([source].concat(observables)), new CombineLatestOperator(project)); };
  2465. }
  2466. var CombineLatestOperator = (function () {
  2467. function CombineLatestOperator(project) {
  2468. this.project = project;
  2469. }
  2470. CombineLatestOperator.prototype.call = function (subscriber, source) {
  2471. return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
  2472. };
  2473. return CombineLatestOperator;
  2474. }());
  2475. /**
  2476. * We need this JSDoc comment for affecting ESDoc.
  2477. * @ignore
  2478. * @extends {Ignored}
  2479. */
  2480. var CombineLatestSubscriber = (function (_super) {
  2481. __extends(CombineLatestSubscriber, _super);
  2482. function CombineLatestSubscriber(destination, project) {
  2483. _super.call(this, destination);
  2484. this.project = project;
  2485. this.active = 0;
  2486. this.values = [];
  2487. this.observables = [];
  2488. }
  2489. CombineLatestSubscriber.prototype._next = function (observable) {
  2490. this.values.push(none);
  2491. this.observables.push(observable);
  2492. };
  2493. CombineLatestSubscriber.prototype._complete = function () {
  2494. var observables = this.observables;
  2495. var len = observables.length;
  2496. if (len === 0) {
  2497. this.destination.complete();
  2498. }
  2499. else {
  2500. this.active = len;
  2501. this.toRespond = len;
  2502. for (var i = 0; i < len; i++) {
  2503. var observable = observables[i];
  2504. this.add(subscribeToResult(this, observable, observable, i));
  2505. }
  2506. }
  2507. };
  2508. CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
  2509. if ((this.active -= 1) === 0) {
  2510. this.destination.complete();
  2511. }
  2512. };
  2513. CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  2514. var values = this.values;
  2515. var oldVal = values[outerIndex];
  2516. var toRespond = !this.toRespond
  2517. ? 0
  2518. : oldVal === none ? --this.toRespond : this.toRespond;
  2519. values[outerIndex] = innerValue;
  2520. if (toRespond === 0) {
  2521. if (this.project) {
  2522. this._tryProject(values);
  2523. }
  2524. else {
  2525. this.destination.next(values.slice());
  2526. }
  2527. }
  2528. };
  2529. CombineLatestSubscriber.prototype._tryProject = function (values) {
  2530. var result;
  2531. try {
  2532. result = this.project.apply(this, values);
  2533. }
  2534. catch (err) {
  2535. this.destination.error(err);
  2536. return;
  2537. }
  2538. this.destination.next(result);
  2539. };
  2540. return CombineLatestSubscriber;
  2541. }(OuterSubscriber));
  2542. /* tslint:enable:max-line-length */
  2543. /**
  2544. * Combines multiple Observables to create an Observable whose values are
  2545. * calculated from the latest values of each of its input Observables.
  2546. *
  2547. * <span class="informal">Whenever any input Observable emits a value, it
  2548. * computes a formula using the latest values from all the inputs, then emits
  2549. * the output of that formula.</span>
  2550. *
  2551. * <img src="./img/combineLatest.png" width="100%">
  2552. *
  2553. * `combineLatest` combines the values from all the Observables passed as
  2554. * arguments. This is done by subscribing to each Observable in order and,
  2555. * whenever any Observable emits, collecting an array of the most recent
  2556. * values from each Observable. So if you pass `n` Observables to operator,
  2557. * returned Observable will always emit an array of `n` values, in order
  2558. * corresponding to order of passed Observables (value from the first Observable
  2559. * on the first place and so on).
  2560. *
  2561. * Static version of `combineLatest` accepts either an array of Observables
  2562. * or each Observable can be put directly as an argument. Note that array of
  2563. * Observables is good choice, if you don't know beforehand how many Observables
  2564. * you will combine. Passing empty array will result in Observable that
  2565. * completes immediately.
  2566. *
  2567. * To ensure output array has always the same length, `combineLatest` will
  2568. * actually wait for all input Observables to emit at least once,
  2569. * before it starts emitting results. This means if some Observable emits
  2570. * values before other Observables started emitting, all that values but last
  2571. * will be lost. On the other hand, is some Observable does not emit value but
  2572. * completes, resulting Observable will complete at the same moment without
  2573. * emitting anything, since it will be now impossible to include value from
  2574. * completed Observable in resulting array. Also, if some input Observable does
  2575. * not emit any value and never completes, `combineLatest` will also never emit
  2576. * and never complete, since, again, it will wait for all streams to emit some
  2577. * value.
  2578. *
  2579. * If at least one Observable was passed to `combineLatest` and all passed Observables
  2580. * emitted something, resulting Observable will complete when all combined
  2581. * streams complete. So even if some Observable completes, result of
  2582. * `combineLatest` will still emit values when other Observables do. In case
  2583. * of completed Observable, its value from now on will always be the last
  2584. * emitted value. On the other hand, if any Observable errors, `combineLatest`
  2585. * will error immediately as well, and all other Observables will be unsubscribed.
  2586. *
  2587. * `combineLatest` accepts as optional parameter `project` function, which takes
  2588. * as arguments all values that would normally be emitted by resulting Observable.
  2589. * `project` can return any kind of value, which will be then emitted by Observable
  2590. * instead of default array. Note that `project` does not take as argument that array
  2591. * of values, but values themselves. That means default `project` can be imagined
  2592. * as function that takes all its arguments and puts them into an array.
  2593. *
  2594. *
  2595. * @example <caption>Combine two timer Observables</caption>
  2596. * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
  2597. * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
  2598. * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
  2599. * combinedTimers.subscribe(value => console.log(value));
  2600. * // Logs
  2601. * // [0, 0] after 0.5s
  2602. * // [1, 0] after 1s
  2603. * // [1, 1] after 1.5s
  2604. * // [2, 1] after 2s
  2605. *
  2606. *
  2607. * @example <caption>Combine an array of Observables</caption>
  2608. * const observables = [1, 5, 10].map(
  2609. * n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
  2610. * );
  2611. * const combined = Rx.Observable.combineLatest(observables);
  2612. * combined.subscribe(value => console.log(value));
  2613. * // Logs
  2614. * // [0, 0, 0] immediately
  2615. * // [1, 0, 0] after 1s
  2616. * // [1, 5, 0] after 5s
  2617. * // [1, 5, 10] after 10s
  2618. *
  2619. *
  2620. * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
  2621. * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
  2622. * var height = Rx.Observable.of(1.76, 1.77, 1.78);
  2623. * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
  2624. * bmi.subscribe(x => console.log('BMI is ' + x));
  2625. *
  2626. * // With output to console:
  2627. * // BMI is 24.212293388429753
  2628. * // BMI is 23.93948099205209
  2629. * // BMI is 23.671253629592222
  2630. *
  2631. *
  2632. * @see {@link combineAll}
  2633. * @see {@link merge}
  2634. * @see {@link withLatestFrom}
  2635. *
  2636. * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
  2637. * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
  2638. * More than one input Observables may be given as arguments
  2639. * or an array of Observables may be given as the first argument.
  2640. * @param {function} [project] An optional function to project the values from
  2641. * the combined latest values into a new value on the output Observable.
  2642. * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
  2643. * each input Observable.
  2644. * @return {Observable} An Observable of projected values from the most recent
  2645. * values from each input Observable, or an array of the most recent values from
  2646. * each input Observable.
  2647. * @static true
  2648. * @name combineLatest
  2649. * @owner Observable
  2650. */
  2651. function combineLatest$$1() {
  2652. var observables = [];
  2653. for (var _i = 0; _i < arguments.length; _i++) {
  2654. observables[_i - 0] = arguments[_i];
  2655. }
  2656. var project = null;
  2657. var scheduler = null;
  2658. if (isScheduler(observables[observables.length - 1])) {
  2659. scheduler = observables.pop();
  2660. }
  2661. if (typeof observables[observables.length - 1] === 'function') {
  2662. project = observables.pop();
  2663. }
  2664. // if the first and only other argument besides the resultSelector is an array
  2665. // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
  2666. if (observables.length === 1 && isArray(observables[0])) {
  2667. observables = observables[0];
  2668. }
  2669. return new ArrayObservable(observables, scheduler).lift(new CombineLatestOperator(project));
  2670. }
  2671. Observable.combineLatest = combineLatest$$1;
  2672. var of = ArrayObservable.of;
  2673. /**
  2674. * We need this JSDoc comment for affecting ESDoc.
  2675. * @extends {Ignored}
  2676. * @hide true
  2677. */
  2678. var PromiseObservable = (function (_super) {
  2679. __extends(PromiseObservable, _super);
  2680. function PromiseObservable(promise, scheduler) {
  2681. _super.call(this);
  2682. this.promise = promise;
  2683. this.scheduler = scheduler;
  2684. }
  2685. /**
  2686. * Converts a Promise to an Observable.
  2687. *
  2688. * <span class="informal">Returns an Observable that just emits the Promise's
  2689. * resolved value, then completes.</span>
  2690. *
  2691. * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
  2692. * Observable. If the Promise resolves with a value, the output Observable
  2693. * emits that resolved value as a `next`, and then completes. If the Promise
  2694. * is rejected, then the output Observable emits the corresponding Error.
  2695. *
  2696. * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
  2697. * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
  2698. * result.subscribe(x => console.log(x), e => console.error(e));
  2699. *
  2700. * @see {@link bindCallback}
  2701. * @see {@link from}
  2702. *
  2703. * @param {PromiseLike<T>} promise The promise to be converted.
  2704. * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
  2705. * the delivery of the resolved value (or the rejection).
  2706. * @return {Observable<T>} An Observable which wraps the Promise.
  2707. * @static true
  2708. * @name fromPromise
  2709. * @owner Observable
  2710. */
  2711. PromiseObservable.create = function (promise, scheduler) {
  2712. return new PromiseObservable(promise, scheduler);
  2713. };
  2714. /** @deprecated internal use only */ PromiseObservable.prototype._subscribe = function (subscriber) {
  2715. var _this = this;
  2716. var promise = this.promise;
  2717. var scheduler = this.scheduler;
  2718. if (scheduler == null) {
  2719. if (this._isScalar) {
  2720. if (!subscriber.closed) {
  2721. subscriber.next(this.value);
  2722. subscriber.complete();
  2723. }
  2724. }
  2725. else {
  2726. promise.then(function (value) {
  2727. _this.value = value;
  2728. _this._isScalar = true;
  2729. if (!subscriber.closed) {
  2730. subscriber.next(value);
  2731. subscriber.complete();
  2732. }
  2733. }, function (err) {
  2734. if (!subscriber.closed) {
  2735. subscriber.error(err);
  2736. }
  2737. })
  2738. .then(null, function (err) {
  2739. // escape the promise trap, throw unhandled errors
  2740. _root.setTimeout(function () { throw err; });
  2741. });
  2742. }
  2743. }
  2744. else {
  2745. if (this._isScalar) {
  2746. if (!subscriber.closed) {
  2747. return scheduler.schedule(dispatchNext$2, 0, { value: this.value, subscriber: subscriber });
  2748. }
  2749. }
  2750. else {
  2751. promise.then(function (value) {
  2752. _this.value = value;
  2753. _this._isScalar = true;
  2754. if (!subscriber.closed) {
  2755. subscriber.add(scheduler.schedule(dispatchNext$2, 0, { value: value, subscriber: subscriber }));
  2756. }
  2757. }, function (err) {
  2758. if (!subscriber.closed) {
  2759. subscriber.add(scheduler.schedule(dispatchError$2, 0, { err: err, subscriber: subscriber }));
  2760. }
  2761. })
  2762. .then(null, function (err) {
  2763. // escape the promise trap, throw unhandled errors
  2764. _root.setTimeout(function () { throw err; });
  2765. });
  2766. }
  2767. }
  2768. };
  2769. return PromiseObservable;
  2770. }(Observable));
  2771. function dispatchNext$2(arg) {
  2772. var value = arg.value, subscriber = arg.subscriber;
  2773. if (!subscriber.closed) {
  2774. subscriber.next(value);
  2775. subscriber.complete();
  2776. }
  2777. }
  2778. function dispatchError$2(arg) {
  2779. var err = arg.err, subscriber = arg.subscriber;
  2780. if (!subscriber.closed) {
  2781. subscriber.error(err);
  2782. }
  2783. }
  2784. /**
  2785. * We need this JSDoc comment for affecting ESDoc.
  2786. * @extends {Ignored}
  2787. * @hide true
  2788. */
  2789. var IteratorObservable = (function (_super) {
  2790. __extends(IteratorObservable, _super);
  2791. function IteratorObservable(iterator$$1, scheduler) {
  2792. _super.call(this);
  2793. this.scheduler = scheduler;
  2794. if (iterator$$1 == null) {
  2795. throw new Error('iterator cannot be null.');
  2796. }
  2797. this.iterator = getIterator(iterator$$1);
  2798. }
  2799. IteratorObservable.create = function (iterator$$1, scheduler) {
  2800. return new IteratorObservable(iterator$$1, scheduler);
  2801. };
  2802. IteratorObservable.dispatch = function (state) {
  2803. var index = state.index, hasError = state.hasError, iterator$$1 = state.iterator, subscriber = state.subscriber;
  2804. if (hasError) {
  2805. subscriber.error(state.error);
  2806. return;
  2807. }
  2808. var result = iterator$$1.next();
  2809. if (result.done) {
  2810. subscriber.complete();
  2811. return;
  2812. }
  2813. subscriber.next(result.value);
  2814. state.index = index + 1;
  2815. if (subscriber.closed) {
  2816. if (typeof iterator$$1.return === 'function') {
  2817. iterator$$1.return();
  2818. }
  2819. return;
  2820. }
  2821. this.schedule(state);
  2822. };
  2823. /** @deprecated internal use only */ IteratorObservable.prototype._subscribe = function (subscriber) {
  2824. var index = 0;
  2825. var _a = this, iterator$$1 = _a.iterator, scheduler = _a.scheduler;
  2826. if (scheduler) {
  2827. return scheduler.schedule(IteratorObservable.dispatch, 0, {
  2828. index: index, iterator: iterator$$1, subscriber: subscriber
  2829. });
  2830. }
  2831. else {
  2832. do {
  2833. var result = iterator$$1.next();
  2834. if (result.done) {
  2835. subscriber.complete();
  2836. break;
  2837. }
  2838. else {
  2839. subscriber.next(result.value);
  2840. }
  2841. if (subscriber.closed) {
  2842. if (typeof iterator$$1.return === 'function') {
  2843. iterator$$1.return();
  2844. }
  2845. break;
  2846. }
  2847. } while (true);
  2848. }
  2849. };
  2850. return IteratorObservable;
  2851. }(Observable));
  2852. var StringIterator = (function () {
  2853. function StringIterator(str, idx, len) {
  2854. if (idx === void 0) { idx = 0; }
  2855. if (len === void 0) { len = str.length; }
  2856. this.str = str;
  2857. this.idx = idx;
  2858. this.len = len;
  2859. }
  2860. StringIterator.prototype[iterator] = function () { return (this); };
  2861. StringIterator.prototype.next = function () {
  2862. return this.idx < this.len ? {
  2863. done: false,
  2864. value: this.str.charAt(this.idx++)
  2865. } : {
  2866. done: true,
  2867. value: undefined
  2868. };
  2869. };
  2870. return StringIterator;
  2871. }());
  2872. var ArrayIterator = (function () {
  2873. function ArrayIterator(arr, idx, len) {
  2874. if (idx === void 0) { idx = 0; }
  2875. if (len === void 0) { len = toLength(arr); }
  2876. this.arr = arr;
  2877. this.idx = idx;
  2878. this.len = len;
  2879. }
  2880. ArrayIterator.prototype[iterator] = function () { return this; };
  2881. ArrayIterator.prototype.next = function () {
  2882. return this.idx < this.len ? {
  2883. done: false,
  2884. value: this.arr[this.idx++]
  2885. } : {
  2886. done: true,
  2887. value: undefined
  2888. };
  2889. };
  2890. return ArrayIterator;
  2891. }());
  2892. function getIterator(obj) {
  2893. var i = obj[iterator];
  2894. if (!i && typeof obj === 'string') {
  2895. return new StringIterator(obj);
  2896. }
  2897. if (!i && obj.length !== undefined) {
  2898. return new ArrayIterator(obj);
  2899. }
  2900. if (!i) {
  2901. throw new TypeError('object is not iterable');
  2902. }
  2903. return obj[iterator]();
  2904. }
  2905. var maxSafeInteger = Math.pow(2, 53) - 1;
  2906. function toLength(o) {
  2907. var len = +o.length;
  2908. if (isNaN(len)) {
  2909. return 0;
  2910. }
  2911. if (len === 0 || !numberIsFinite(len)) {
  2912. return len;
  2913. }
  2914. len = sign(len) * Math.floor(Math.abs(len));
  2915. if (len <= 0) {
  2916. return 0;
  2917. }
  2918. if (len > maxSafeInteger) {
  2919. return maxSafeInteger;
  2920. }
  2921. return len;
  2922. }
  2923. function numberIsFinite(value) {
  2924. return typeof value === 'number' && _root.isFinite(value);
  2925. }
  2926. function sign(value) {
  2927. var valueAsNumber = +value;
  2928. if (valueAsNumber === 0) {
  2929. return valueAsNumber;
  2930. }
  2931. if (isNaN(valueAsNumber)) {
  2932. return valueAsNumber;
  2933. }
  2934. return valueAsNumber < 0 ? -1 : 1;
  2935. }
  2936. /**
  2937. * We need this JSDoc comment for affecting ESDoc.
  2938. * @extends {Ignored}
  2939. * @hide true
  2940. */
  2941. var ArrayLikeObservable = (function (_super) {
  2942. __extends(ArrayLikeObservable, _super);
  2943. function ArrayLikeObservable(arrayLike, scheduler) {
  2944. _super.call(this);
  2945. this.arrayLike = arrayLike;
  2946. this.scheduler = scheduler;
  2947. if (!scheduler && arrayLike.length === 1) {
  2948. this._isScalar = true;
  2949. this.value = arrayLike[0];
  2950. }
  2951. }
  2952. ArrayLikeObservable.create = function (arrayLike, scheduler) {
  2953. var length = arrayLike.length;
  2954. if (length === 0) {
  2955. return new EmptyObservable();
  2956. }
  2957. else if (length === 1) {
  2958. return new ScalarObservable(arrayLike[0], scheduler);
  2959. }
  2960. else {
  2961. return new ArrayLikeObservable(arrayLike, scheduler);
  2962. }
  2963. };
  2964. ArrayLikeObservable.dispatch = function (state) {
  2965. var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
  2966. if (subscriber.closed) {
  2967. return;
  2968. }
  2969. if (index >= length) {
  2970. subscriber.complete();
  2971. return;
  2972. }
  2973. subscriber.next(arrayLike[index]);
  2974. state.index = index + 1;
  2975. this.schedule(state);
  2976. };
  2977. /** @deprecated internal use only */ ArrayLikeObservable.prototype._subscribe = function (subscriber) {
  2978. var index = 0;
  2979. var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
  2980. var length = arrayLike.length;
  2981. if (scheduler) {
  2982. return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
  2983. arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
  2984. });
  2985. }
  2986. else {
  2987. for (var i = 0; i < length && !subscriber.closed; i++) {
  2988. subscriber.next(arrayLike[i]);
  2989. }
  2990. subscriber.complete();
  2991. }
  2992. };
  2993. return ArrayLikeObservable;
  2994. }(Observable));
  2995. /**
  2996. * Represents a push-based event or value that an {@link Observable} can emit.
  2997. * This class is particularly useful for operators that manage notifications,
  2998. * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
  2999. * others. Besides wrapping the actual delivered value, it also annotates it
  3000. * with metadata of, for instance, what type of push message it is (`next`,
  3001. * `error`, or `complete`).
  3002. *
  3003. * @see {@link materialize}
  3004. * @see {@link dematerialize}
  3005. * @see {@link observeOn}
  3006. *
  3007. * @class Notification<T>
  3008. */
  3009. var Notification = (function () {
  3010. function Notification(kind, value, error) {
  3011. this.kind = kind;
  3012. this.value = value;
  3013. this.error = error;
  3014. this.hasValue = kind === 'N';
  3015. }
  3016. /**
  3017. * Delivers to the given `observer` the value wrapped by this Notification.
  3018. * @param {Observer} observer
  3019. * @return
  3020. */
  3021. Notification.prototype.observe = function (observer) {
  3022. switch (this.kind) {
  3023. case 'N':
  3024. return observer.next && observer.next(this.value);
  3025. case 'E':
  3026. return observer.error && observer.error(this.error);
  3027. case 'C':
  3028. return observer.complete && observer.complete();
  3029. }
  3030. };
  3031. /**
  3032. * Given some {@link Observer} callbacks, deliver the value represented by the
  3033. * current Notification to the correctly corresponding callback.
  3034. * @param {function(value: T): void} next An Observer `next` callback.
  3035. * @param {function(err: any): void} [error] An Observer `error` callback.
  3036. * @param {function(): void} [complete] An Observer `complete` callback.
  3037. * @return {any}
  3038. */
  3039. Notification.prototype.do = function (next, error, complete) {
  3040. var kind = this.kind;
  3041. switch (kind) {
  3042. case 'N':
  3043. return next && next(this.value);
  3044. case 'E':
  3045. return error && error(this.error);
  3046. case 'C':
  3047. return complete && complete();
  3048. }
  3049. };
  3050. /**
  3051. * Takes an Observer or its individual callback functions, and calls `observe`
  3052. * or `do` methods accordingly.
  3053. * @param {Observer|function(value: T): void} nextOrObserver An Observer or
  3054. * the `next` callback.
  3055. * @param {function(err: any): void} [error] An Observer `error` callback.
  3056. * @param {function(): void} [complete] An Observer `complete` callback.
  3057. * @return {any}
  3058. */
  3059. Notification.prototype.accept = function (nextOrObserver, error, complete) {
  3060. if (nextOrObserver && typeof nextOrObserver.next === 'function') {
  3061. return this.observe(nextOrObserver);
  3062. }
  3063. else {
  3064. return this.do(nextOrObserver, error, complete);
  3065. }
  3066. };
  3067. /**
  3068. * Returns a simple Observable that just delivers the notification represented
  3069. * by this Notification instance.
  3070. * @return {any}
  3071. */
  3072. Notification.prototype.toObservable = function () {
  3073. var kind = this.kind;
  3074. switch (kind) {
  3075. case 'N':
  3076. return Observable.of(this.value);
  3077. case 'E':
  3078. return Observable.throw(this.error);
  3079. case 'C':
  3080. return Observable.empty();
  3081. }
  3082. throw new Error('unexpected notification kind value');
  3083. };
  3084. /**
  3085. * A shortcut to create a Notification instance of the type `next` from a
  3086. * given value.
  3087. * @param {T} value The `next` value.
  3088. * @return {Notification<T>} The "next" Notification representing the
  3089. * argument.
  3090. */
  3091. Notification.createNext = function (value) {
  3092. if (typeof value !== 'undefined') {
  3093. return new Notification('N', value);
  3094. }
  3095. return Notification.undefinedValueNotification;
  3096. };
  3097. /**
  3098. * A shortcut to create a Notification instance of the type `error` from a
  3099. * given error.
  3100. * @param {any} [err] The `error` error.
  3101. * @return {Notification<T>} The "error" Notification representing the
  3102. * argument.
  3103. */
  3104. Notification.createError = function (err) {
  3105. return new Notification('E', undefined, err);
  3106. };
  3107. /**
  3108. * A shortcut to create a Notification instance of the type `complete`.
  3109. * @return {Notification<any>} The valueless "complete" Notification.
  3110. */
  3111. Notification.createComplete = function () {
  3112. return Notification.completeNotification;
  3113. };
  3114. Notification.completeNotification = new Notification('C');
  3115. Notification.undefinedValueNotification = new Notification('N', undefined);
  3116. return Notification;
  3117. }());
  3118. /**
  3119. *
  3120. * Re-emits all notifications from source Observable with specified scheduler.
  3121. *
  3122. * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
  3123. *
  3124. * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
  3125. * notifications emitted by the source Observable. It might be useful, if you do not have control over
  3126. * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
  3127. *
  3128. * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
  3129. * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
  3130. * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
  3131. * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
  3132. * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
  3133. * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
  3134. * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
  3135. * little bit more, to ensure that they are emitted at expected moments.
  3136. *
  3137. * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
  3138. * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
  3139. * will delay all notifications - including error notifications - while `delay` will pass through error
  3140. * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
  3141. * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
  3142. * for notification emissions in general.
  3143. *
  3144. * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
  3145. * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
  3146. * // with async scheduler by default...
  3147. *
  3148. * intervals
  3149. * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame
  3150. * .subscribe(val => { // scheduler to ensure smooth animation.
  3151. * someDiv.style.height = val + 'px';
  3152. * });
  3153. *
  3154. * @see {@link delay}
  3155. *
  3156. * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
  3157. * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
  3158. * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
  3159. * but with provided scheduler.
  3160. *
  3161. * @method observeOn
  3162. * @owner Observable
  3163. */
  3164. function observeOn(scheduler, delay) {
  3165. if (delay === void 0) { delay = 0; }
  3166. return function observeOnOperatorFunction(source) {
  3167. return source.lift(new ObserveOnOperator(scheduler, delay));
  3168. };
  3169. }
  3170. var ObserveOnOperator = (function () {
  3171. function ObserveOnOperator(scheduler, delay) {
  3172. if (delay === void 0) { delay = 0; }
  3173. this.scheduler = scheduler;
  3174. this.delay = delay;
  3175. }
  3176. ObserveOnOperator.prototype.call = function (subscriber, source) {
  3177. return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
  3178. };
  3179. return ObserveOnOperator;
  3180. }());
  3181. /**
  3182. * We need this JSDoc comment for affecting ESDoc.
  3183. * @ignore
  3184. * @extends {Ignored}
  3185. */
  3186. var ObserveOnSubscriber = (function (_super) {
  3187. __extends(ObserveOnSubscriber, _super);
  3188. function ObserveOnSubscriber(destination, scheduler, delay) {
  3189. if (delay === void 0) { delay = 0; }
  3190. _super.call(this, destination);
  3191. this.scheduler = scheduler;
  3192. this.delay = delay;
  3193. }
  3194. ObserveOnSubscriber.dispatch = function (arg) {
  3195. var notification = arg.notification, destination = arg.destination;
  3196. notification.observe(destination);
  3197. this.unsubscribe();
  3198. };
  3199. ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
  3200. this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
  3201. };
  3202. ObserveOnSubscriber.prototype._next = function (value) {
  3203. this.scheduleMessage(Notification.createNext(value));
  3204. };
  3205. ObserveOnSubscriber.prototype._error = function (err) {
  3206. this.scheduleMessage(Notification.createError(err));
  3207. };
  3208. ObserveOnSubscriber.prototype._complete = function () {
  3209. this.scheduleMessage(Notification.createComplete());
  3210. };
  3211. return ObserveOnSubscriber;
  3212. }(Subscriber));
  3213. var ObserveOnMessage = (function () {
  3214. function ObserveOnMessage(notification, destination) {
  3215. this.notification = notification;
  3216. this.destination = destination;
  3217. }
  3218. return ObserveOnMessage;
  3219. }());
  3220. /**
  3221. * We need this JSDoc comment for affecting ESDoc.
  3222. * @extends {Ignored}
  3223. * @hide true
  3224. */
  3225. var FromObservable = (function (_super) {
  3226. __extends(FromObservable, _super);
  3227. function FromObservable(ish, scheduler) {
  3228. _super.call(this, null);
  3229. this.ish = ish;
  3230. this.scheduler = scheduler;
  3231. }
  3232. /**
  3233. * Creates an Observable from an Array, an array-like object, a Promise, an
  3234. * iterable object, or an Observable-like object.
  3235. *
  3236. * <span class="informal">Converts almost anything to an Observable.</span>
  3237. *
  3238. * <img src="./img/from.png" width="100%">
  3239. *
  3240. * Convert various other objects and data types into Observables. `from`
  3241. * converts a Promise or an array-like or an
  3242. * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
  3243. * object into an Observable that emits the items in that promise or array or
  3244. * iterable. A String, in this context, is treated as an array of characters.
  3245. * Observable-like objects (contains a function named with the ES2015 Symbol
  3246. * for Observable) can also be converted through this operator.
  3247. *
  3248. * @example <caption>Converts an array to an Observable</caption>
  3249. * var array = [10, 20, 30];
  3250. * var result = Rx.Observable.from(array);
  3251. * result.subscribe(x => console.log(x));
  3252. *
  3253. * // Results in the following:
  3254. * // 10 20 30
  3255. *
  3256. * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
  3257. * function* generateDoubles(seed) {
  3258. * var i = seed;
  3259. * while (true) {
  3260. * yield i;
  3261. * i = 2 * i; // double it
  3262. * }
  3263. * }
  3264. *
  3265. * var iterator = generateDoubles(3);
  3266. * var result = Rx.Observable.from(iterator).take(10);
  3267. * result.subscribe(x => console.log(x));
  3268. *
  3269. * // Results in the following:
  3270. * // 3 6 12 24 48 96 192 384 768 1536
  3271. *
  3272. * @see {@link create}
  3273. * @see {@link fromEvent}
  3274. * @see {@link fromEventPattern}
  3275. * @see {@link fromPromise}
  3276. *
  3277. * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
  3278. * Observable-like, an Array, an iterable or an array-like object to be
  3279. * converted.
  3280. * @param {Scheduler} [scheduler] The scheduler on which to schedule the
  3281. * emissions of values.
  3282. * @return {Observable<T>} The Observable whose values are originally from the
  3283. * input object that was converted.
  3284. * @static true
  3285. * @name from
  3286. * @owner Observable
  3287. */
  3288. FromObservable.create = function (ish, scheduler) {
  3289. if (ish != null) {
  3290. if (typeof ish[observable] === 'function') {
  3291. if (ish instanceof Observable && !scheduler) {
  3292. return ish;
  3293. }
  3294. return new FromObservable(ish, scheduler);
  3295. }
  3296. else if (isArray(ish)) {
  3297. return new ArrayObservable(ish, scheduler);
  3298. }
  3299. else if (isPromise(ish)) {
  3300. return new PromiseObservable(ish, scheduler);
  3301. }
  3302. else if (typeof ish[iterator] === 'function' || typeof ish === 'string') {
  3303. return new IteratorObservable(ish, scheduler);
  3304. }
  3305. else if (isArrayLike(ish)) {
  3306. return new ArrayLikeObservable(ish, scheduler);
  3307. }
  3308. }
  3309. throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
  3310. };
  3311. /** @deprecated internal use only */ FromObservable.prototype._subscribe = function (subscriber) {
  3312. var ish = this.ish;
  3313. var scheduler = this.scheduler;
  3314. if (scheduler == null) {
  3315. return ish[observable]().subscribe(subscriber);
  3316. }
  3317. else {
  3318. return ish[observable]().subscribe(new ObserveOnSubscriber(subscriber, scheduler, 0));
  3319. }
  3320. };
  3321. return FromObservable;
  3322. }(Observable));
  3323. var from = FromObservable.create;
  3324. /* tslint:enable:max-line-length */
  3325. /**
  3326. * Projects each source value to an Observable which is merged in the output
  3327. * Observable.
  3328. *
  3329. * <span class="informal">Maps each value to an Observable, then flattens all of
  3330. * these inner Observables using {@link mergeAll}.</span>
  3331. *
  3332. * <img src="./img/mergeMap.png" width="100%">
  3333. *
  3334. * Returns an Observable that emits items based on applying a function that you
  3335. * supply to each item emitted by the source Observable, where that function
  3336. * returns an Observable, and then merging those resulting Observables and
  3337. * emitting the results of this merger.
  3338. *
  3339. * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
  3340. * var letters = Rx.Observable.of('a', 'b', 'c');
  3341. * var result = letters.mergeMap(x =>
  3342. * Rx.Observable.interval(1000).map(i => x+i)
  3343. * );
  3344. * result.subscribe(x => console.log(x));
  3345. *
  3346. * // Results in the following:
  3347. * // a0
  3348. * // b0
  3349. * // c0
  3350. * // a1
  3351. * // b1
  3352. * // c1
  3353. * // continues to list a,b,c with respective ascending integers
  3354. *
  3355. * @see {@link concatMap}
  3356. * @see {@link exhaustMap}
  3357. * @see {@link merge}
  3358. * @see {@link mergeAll}
  3359. * @see {@link mergeMapTo}
  3360. * @see {@link mergeScan}
  3361. * @see {@link switchMap}
  3362. *
  3363. * @param {function(value: T, ?index: number): ObservableInput} project A function
  3364. * that, when applied to an item emitted by the source Observable, returns an
  3365. * Observable.
  3366. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  3367. * A function to produce the value on the output Observable based on the values
  3368. * and the indices of the source (outer) emission and the inner Observable
  3369. * emission. The arguments passed to this function are:
  3370. * - `outerValue`: the value that came from the source
  3371. * - `innerValue`: the value that came from the projected Observable
  3372. * - `outerIndex`: the "index" of the value that came from the source
  3373. * - `innerIndex`: the "index" of the value from the projected Observable
  3374. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  3375. * Observables being subscribed to concurrently.
  3376. * @return {Observable} An Observable that emits the result of applying the
  3377. * projection function (and the optional `resultSelector`) to each item emitted
  3378. * by the source Observable and merging the results of the Observables obtained
  3379. * from this transformation.
  3380. * @method mergeMap
  3381. * @owner Observable
  3382. */
  3383. function mergeMap(project, resultSelector, concurrent) {
  3384. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  3385. return function mergeMapOperatorFunction(source) {
  3386. if (typeof resultSelector === 'number') {
  3387. concurrent = resultSelector;
  3388. resultSelector = null;
  3389. }
  3390. return source.lift(new MergeMapOperator(project, resultSelector, concurrent));
  3391. };
  3392. }
  3393. var MergeMapOperator = (function () {
  3394. function MergeMapOperator(project, resultSelector, concurrent) {
  3395. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  3396. this.project = project;
  3397. this.resultSelector = resultSelector;
  3398. this.concurrent = concurrent;
  3399. }
  3400. MergeMapOperator.prototype.call = function (observer, source) {
  3401. return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
  3402. };
  3403. return MergeMapOperator;
  3404. }());
  3405. /**
  3406. * We need this JSDoc comment for affecting ESDoc.
  3407. * @ignore
  3408. * @extends {Ignored}
  3409. */
  3410. var MergeMapSubscriber = (function (_super) {
  3411. __extends(MergeMapSubscriber, _super);
  3412. function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
  3413. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  3414. _super.call(this, destination);
  3415. this.project = project;
  3416. this.resultSelector = resultSelector;
  3417. this.concurrent = concurrent;
  3418. this.hasCompleted = false;
  3419. this.buffer = [];
  3420. this.active = 0;
  3421. this.index = 0;
  3422. }
  3423. MergeMapSubscriber.prototype._next = function (value) {
  3424. if (this.active < this.concurrent) {
  3425. this._tryNext(value);
  3426. }
  3427. else {
  3428. this.buffer.push(value);
  3429. }
  3430. };
  3431. MergeMapSubscriber.prototype._tryNext = function (value) {
  3432. var result;
  3433. var index = this.index++;
  3434. try {
  3435. result = this.project(value, index);
  3436. }
  3437. catch (err) {
  3438. this.destination.error(err);
  3439. return;
  3440. }
  3441. this.active++;
  3442. this._innerSub(result, value, index);
  3443. };
  3444. MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
  3445. this.add(subscribeToResult(this, ish, value, index));
  3446. };
  3447. MergeMapSubscriber.prototype._complete = function () {
  3448. this.hasCompleted = true;
  3449. if (this.active === 0 && this.buffer.length === 0) {
  3450. this.destination.complete();
  3451. }
  3452. };
  3453. MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  3454. if (this.resultSelector) {
  3455. this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
  3456. }
  3457. else {
  3458. this.destination.next(innerValue);
  3459. }
  3460. };
  3461. MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
  3462. var result;
  3463. try {
  3464. result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
  3465. }
  3466. catch (err) {
  3467. this.destination.error(err);
  3468. return;
  3469. }
  3470. this.destination.next(result);
  3471. };
  3472. MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
  3473. var buffer = this.buffer;
  3474. this.remove(innerSub);
  3475. this.active--;
  3476. if (buffer.length > 0) {
  3477. this._next(buffer.shift());
  3478. }
  3479. else if (this.active === 0 && this.hasCompleted) {
  3480. this.destination.complete();
  3481. }
  3482. };
  3483. return MergeMapSubscriber;
  3484. }(OuterSubscriber));
  3485. function identity(x) {
  3486. return x;
  3487. }
  3488. /**
  3489. * Converts a higher-order Observable into a first-order Observable which
  3490. * concurrently delivers all values that are emitted on the inner Observables.
  3491. *
  3492. * <span class="informal">Flattens an Observable-of-Observables.</span>
  3493. *
  3494. * <img src="./img/mergeAll.png" width="100%">
  3495. *
  3496. * `mergeAll` subscribes to an Observable that emits Observables, also known as
  3497. * a higher-order Observable. Each time it observes one of these emitted inner
  3498. * Observables, it subscribes to that and delivers all the values from the
  3499. * inner Observable on the output Observable. The output Observable only
  3500. * completes once all inner Observables have completed. Any error delivered by
  3501. * a inner Observable will be immediately emitted on the output Observable.
  3502. *
  3503. * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
  3504. * var clicks = Rx.Observable.fromEvent(document, 'click');
  3505. * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
  3506. * var firstOrder = higherOrder.mergeAll();
  3507. * firstOrder.subscribe(x => console.log(x));
  3508. *
  3509. * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
  3510. * var clicks = Rx.Observable.fromEvent(document, 'click');
  3511. * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
  3512. * var firstOrder = higherOrder.mergeAll(2);
  3513. * firstOrder.subscribe(x => console.log(x));
  3514. *
  3515. * @see {@link combineAll}
  3516. * @see {@link concatAll}
  3517. * @see {@link exhaust}
  3518. * @see {@link merge}
  3519. * @see {@link mergeMap}
  3520. * @see {@link mergeMapTo}
  3521. * @see {@link mergeScan}
  3522. * @see {@link switch}
  3523. * @see {@link zipAll}
  3524. *
  3525. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
  3526. * Observables being subscribed to concurrently.
  3527. * @return {Observable} An Observable that emits values coming from all the
  3528. * inner Observables emitted by the source Observable.
  3529. * @method mergeAll
  3530. * @owner Observable
  3531. */
  3532. function mergeAll(concurrent) {
  3533. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  3534. return mergeMap(identity, null, concurrent);
  3535. }
  3536. /**
  3537. * Converts a higher-order Observable into a first-order Observable by
  3538. * concatenating the inner Observables in order.
  3539. *
  3540. * <span class="informal">Flattens an Observable-of-Observables by putting one
  3541. * inner Observable after the other.</span>
  3542. *
  3543. * <img src="./img/concatAll.png" width="100%">
  3544. *
  3545. * Joins every Observable emitted by the source (a higher-order Observable), in
  3546. * a serial fashion. It subscribes to each inner Observable only after the
  3547. * previous inner Observable has completed, and merges all of their values into
  3548. * the returned observable.
  3549. *
  3550. * __Warning:__ If the source Observable emits Observables quickly and
  3551. * endlessly, and the inner Observables it emits generally complete slower than
  3552. * the source emits, you can run into memory issues as the incoming Observables
  3553. * collect in an unbounded buffer.
  3554. *
  3555. * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
  3556. * to `1`.
  3557. *
  3558. * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
  3559. * var clicks = Rx.Observable.fromEvent(document, 'click');
  3560. * var higherOrder = clicks.map(ev => Rx.Observable.interval(1000).take(4));
  3561. * var firstOrder = higherOrder.concatAll();
  3562. * firstOrder.subscribe(x => console.log(x));
  3563. *
  3564. * // Results in the following:
  3565. * // (results are not concurrent)
  3566. * // For every click on the "document" it will emit values 0 to 3 spaced
  3567. * // on a 1000ms interval
  3568. * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
  3569. *
  3570. * @see {@link combineAll}
  3571. * @see {@link concat}
  3572. * @see {@link concatMap}
  3573. * @see {@link concatMapTo}
  3574. * @see {@link exhaust}
  3575. * @see {@link mergeAll}
  3576. * @see {@link switch}
  3577. * @see {@link zipAll}
  3578. *
  3579. * @return {Observable} An Observable emitting values from all the inner
  3580. * Observables concatenated.
  3581. * @method concatAll
  3582. * @owner Observable
  3583. */
  3584. function concatAll() {
  3585. return mergeAll(1);
  3586. }
  3587. /* tslint:enable:max-line-length */
  3588. /**
  3589. * Creates an output Observable which sequentially emits all values from given
  3590. * Observable and then moves on to the next.
  3591. *
  3592. * <span class="informal">Concatenates multiple Observables together by
  3593. * sequentially emitting their values, one Observable after the other.</span>
  3594. *
  3595. * <img src="./img/concat.png" width="100%">
  3596. *
  3597. * `concat` joins multiple Observables together, by subscribing to them one at a time and
  3598. * merging their results into the output Observable. You can pass either an array of
  3599. * Observables, or put them directly as arguments. Passing an empty array will result
  3600. * in Observable that completes immediately.
  3601. *
  3602. * `concat` will subscribe to first input Observable and emit all its values, without
  3603. * changing or affecting them in any way. When that Observable completes, it will
  3604. * subscribe to then next Observable passed and, again, emit its values. This will be
  3605. * repeated, until the operator runs out of Observables. When last input Observable completes,
  3606. * `concat` will complete as well. At any given moment only one Observable passed to operator
  3607. * emits values. If you would like to emit values from passed Observables concurrently, check out
  3608. * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
  3609. * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
  3610. *
  3611. * Note that if some input Observable never completes, `concat` will also never complete
  3612. * and Observables following the one that did not complete will never be subscribed. On the other
  3613. * hand, if some Observable simply completes immediately after it is subscribed, it will be
  3614. * invisible for `concat`, which will just move on to the next Observable.
  3615. *
  3616. * If any Observable in chain errors, instead of passing control to the next Observable,
  3617. * `concat` will error immediately as well. Observables that would be subscribed after
  3618. * the one that emitted error, never will.
  3619. *
  3620. * If you pass to `concat` the same Observable many times, its stream of values
  3621. * will be "replayed" on every subscription, which means you can repeat given Observable
  3622. * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
  3623. * you can always use {@link repeat}.
  3624. *
  3625. * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
  3626. * var timer = Rx.Observable.interval(1000).take(4);
  3627. * var sequence = Rx.Observable.range(1, 10);
  3628. * var result = Rx.Observable.concat(timer, sequence);
  3629. * result.subscribe(x => console.log(x));
  3630. *
  3631. * // results in:
  3632. * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
  3633. *
  3634. *
  3635. * @example <caption>Concatenate an array of 3 Observables</caption>
  3636. * var timer1 = Rx.Observable.interval(1000).take(10);
  3637. * var timer2 = Rx.Observable.interval(2000).take(6);
  3638. * var timer3 = Rx.Observable.interval(500).take(10);
  3639. * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
  3640. * result.subscribe(x => console.log(x));
  3641. *
  3642. * // results in the following:
  3643. * // (Prints to console sequentially)
  3644. * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
  3645. * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
  3646. * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
  3647. *
  3648. *
  3649. * @example <caption>Concatenate the same Observable to repeat it</caption>
  3650. * const timer = Rx.Observable.interval(1000).take(2);
  3651. *
  3652. * Rx.Observable.concat(timer, timer) // concating the same Observable!
  3653. * .subscribe(
  3654. * value => console.log(value),
  3655. * err => {},
  3656. * () => console.log('...and it is done!')
  3657. * );
  3658. *
  3659. * // Logs:
  3660. * // 0 after 1s
  3661. * // 1 after 2s
  3662. * // 0 after 3s
  3663. * // 1 after 4s
  3664. * // "...and it is done!" also after 4s
  3665. *
  3666. * @see {@link concatAll}
  3667. * @see {@link concatMap}
  3668. * @see {@link concatMapTo}
  3669. *
  3670. * @param {ObservableInput} input1 An input Observable to concatenate with others.
  3671. * @param {ObservableInput} input2 An input Observable to concatenate with others.
  3672. * More than one input Observables may be given as argument.
  3673. * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
  3674. * Observable subscription on.
  3675. * @return {Observable} All values of each passed Observable merged into a
  3676. * single Observable, in order, in serial fashion.
  3677. * @static true
  3678. * @name concat
  3679. * @owner Observable
  3680. */
  3681. function concat() {
  3682. var observables = [];
  3683. for (var _i = 0; _i < arguments.length; _i++) {
  3684. observables[_i - 0] = arguments[_i];
  3685. }
  3686. if (observables.length === 1 || (observables.length === 2 && isScheduler(observables[1]))) {
  3687. return from(observables[0]);
  3688. }
  3689. return concatAll()(of.apply(void 0, observables));
  3690. }
  3691. Observable.concat = concat;
  3692. /**
  3693. * We need this JSDoc comment for affecting ESDoc.
  3694. * @extends {Ignored}
  3695. * @hide true
  3696. */
  3697. var DeferObservable = (function (_super) {
  3698. __extends(DeferObservable, _super);
  3699. function DeferObservable(observableFactory) {
  3700. _super.call(this);
  3701. this.observableFactory = observableFactory;
  3702. }
  3703. /**
  3704. * Creates an Observable that, on subscribe, calls an Observable factory to
  3705. * make an Observable for each new Observer.
  3706. *
  3707. * <span class="informal">Creates the Observable lazily, that is, only when it
  3708. * is subscribed.
  3709. * </span>
  3710. *
  3711. * <img src="./img/defer.png" width="100%">
  3712. *
  3713. * `defer` allows you to create the Observable only when the Observer
  3714. * subscribes, and create a fresh Observable for each Observer. It waits until
  3715. * an Observer subscribes to it, and then it generates an Observable,
  3716. * typically with an Observable factory function. It does this afresh for each
  3717. * subscriber, so although each subscriber may think it is subscribing to the
  3718. * same Observable, in fact each subscriber gets its own individual
  3719. * Observable.
  3720. *
  3721. * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
  3722. * var clicksOrInterval = Rx.Observable.defer(function () {
  3723. * if (Math.random() > 0.5) {
  3724. * return Rx.Observable.fromEvent(document, 'click');
  3725. * } else {
  3726. * return Rx.Observable.interval(1000);
  3727. * }
  3728. * });
  3729. * clicksOrInterval.subscribe(x => console.log(x));
  3730. *
  3731. * // Results in the following behavior:
  3732. * // If the result of Math.random() is greater than 0.5 it will listen
  3733. * // for clicks anywhere on the "document"; when document is clicked it
  3734. * // will log a MouseEvent object to the console. If the result is less
  3735. * // than 0.5 it will emit ascending numbers, one every second(1000ms).
  3736. *
  3737. * @see {@link create}
  3738. *
  3739. * @param {function(): SubscribableOrPromise} observableFactory The Observable
  3740. * factory function to invoke for each Observer that subscribes to the output
  3741. * Observable. May also return a Promise, which will be converted on the fly
  3742. * to an Observable.
  3743. * @return {Observable} An Observable whose Observers' subscriptions trigger
  3744. * an invocation of the given Observable factory function.
  3745. * @static true
  3746. * @name defer
  3747. * @owner Observable
  3748. */
  3749. DeferObservable.create = function (observableFactory) {
  3750. return new DeferObservable(observableFactory);
  3751. };
  3752. /** @deprecated internal use only */ DeferObservable.prototype._subscribe = function (subscriber) {
  3753. return new DeferSubscriber(subscriber, this.observableFactory);
  3754. };
  3755. return DeferObservable;
  3756. }(Observable));
  3757. var DeferSubscriber = (function (_super) {
  3758. __extends(DeferSubscriber, _super);
  3759. function DeferSubscriber(destination, factory) {
  3760. _super.call(this, destination);
  3761. this.factory = factory;
  3762. this.tryDefer();
  3763. }
  3764. DeferSubscriber.prototype.tryDefer = function () {
  3765. try {
  3766. this._callFactory();
  3767. }
  3768. catch (err) {
  3769. this._error(err);
  3770. }
  3771. };
  3772. DeferSubscriber.prototype._callFactory = function () {
  3773. var result = this.factory();
  3774. if (result) {
  3775. this.add(subscribeToResult(this, result));
  3776. }
  3777. };
  3778. return DeferSubscriber;
  3779. }(OuterSubscriber));
  3780. var defer = DeferObservable.create;
  3781. Observable.defer = defer;
  3782. var empty$1 = EmptyObservable.create;
  3783. Observable.empty = empty$1;
  3784. /**
  3785. * We need this JSDoc comment for affecting ESDoc.
  3786. * @extends {Ignored}
  3787. * @hide true
  3788. */
  3789. var ForkJoinObservable = (function (_super) {
  3790. __extends(ForkJoinObservable, _super);
  3791. function ForkJoinObservable(sources, resultSelector) {
  3792. _super.call(this);
  3793. this.sources = sources;
  3794. this.resultSelector = resultSelector;
  3795. }
  3796. /* tslint:enable:max-line-length */
  3797. /**
  3798. * Joins last values emitted by passed Observables.
  3799. *
  3800. * <span class="informal">Wait for Observables to complete and then combine last values they emitted.</span>
  3801. *
  3802. * <img src="./img/forkJoin.png" width="100%">
  3803. *
  3804. * `forkJoin` is an operator that takes any number of Observables which can be passed either as an array
  3805. * or directly as arguments. If no input Observables are provided, resulting stream will complete
  3806. * immediately.
  3807. *
  3808. * `forkJoin` will wait for all passed Observables to complete and then it will emit an array with last
  3809. * values from corresponding Observables. So if you pass `n` Observables to the operator, resulting
  3810. * array will have `n` values, where first value is the last thing emitted by the first Observable,
  3811. * second value is the last thing emitted by the second Observable and so on. That means `forkJoin` will
  3812. * not emit more than once and it will complete after that. If you need to emit combined values not only
  3813. * at the end of lifecycle of passed Observables, but also throughout it, try out {@link combineLatest}
  3814. * or {@link zip} instead.
  3815. *
  3816. * In order for resulting array to have the same length as the number of input Observables, whenever any of
  3817. * that Observables completes without emitting any value, `forkJoin` will complete at that moment as well
  3818. * and it will not emit anything either, even if it already has some last values from other Observables.
  3819. * Conversely, if there is an Observable that never completes, `forkJoin` will never complete as well,
  3820. * unless at any point some other Observable completes without emitting value, which brings us back to
  3821. * the previous case. Overall, in order for `forkJoin` to emit a value, all Observables passed as arguments
  3822. * have to emit something at least once and complete.
  3823. *
  3824. * If any input Observable errors at some point, `forkJoin` will error as well and all other Observables
  3825. * will be immediately unsubscribed.
  3826. *
  3827. * Optionally `forkJoin` accepts project function, that will be called with values which normally
  3828. * would land in emitted array. Whatever is returned by project function, will appear in output
  3829. * Observable instead. This means that default project can be thought of as a function that takes
  3830. * all its arguments and puts them into an array. Note that project function will be called only
  3831. * when output Observable is supposed to emit a result.
  3832. *
  3833. * @example <caption>Use forkJoin with operator emitting immediately</caption>
  3834. * const observable = Rx.Observable.forkJoin(
  3835. * Rx.Observable.of(1, 2, 3, 4),
  3836. * Rx.Observable.of(5, 6, 7, 8)
  3837. * );
  3838. * observable.subscribe(
  3839. * value => console.log(value),
  3840. * err => {},
  3841. * () => console.log('This is how it ends!')
  3842. * );
  3843. *
  3844. * // Logs:
  3845. * // [4, 8]
  3846. * // "This is how it ends!"
  3847. *
  3848. *
  3849. * @example <caption>Use forkJoin with operator emitting after some time</caption>
  3850. * const observable = Rx.Observable.forkJoin(
  3851. * Rx.Observable.interval(1000).take(3), // emit 0, 1, 2 every second and complete
  3852. * Rx.Observable.interval(500).take(4) // emit 0, 1, 2, 3 every half a second and complete
  3853. * );
  3854. * observable.subscribe(
  3855. * value => console.log(value),
  3856. * err => {},
  3857. * () => console.log('This is how it ends!')
  3858. * );
  3859. *
  3860. * // Logs:
  3861. * // [2, 3] after 3 seconds
  3862. * // "This is how it ends!" immediately after
  3863. *
  3864. *
  3865. * @example <caption>Use forkJoin with project function</caption>
  3866. * const observable = Rx.Observable.forkJoin(
  3867. * Rx.Observable.interval(1000).take(3), // emit 0, 1, 2 every second and complete
  3868. * Rx.Observable.interval(500).take(4), // emit 0, 1, 2, 3 every half a second and complete
  3869. * (n, m) => n + m
  3870. * );
  3871. * observable.subscribe(
  3872. * value => console.log(value),
  3873. * err => {},
  3874. * () => console.log('This is how it ends!')
  3875. * );
  3876. *
  3877. * // Logs:
  3878. * // 5 after 3 seconds
  3879. * // "This is how it ends!" immediately after
  3880. *
  3881. * @see {@link combineLatest}
  3882. * @see {@link zip}
  3883. *
  3884. * @param {...SubscribableOrPromise} sources Any number of Observables provided either as an array or as an arguments
  3885. * passed directly to the operator.
  3886. * @param {function} [project] Function that takes values emitted by input Observables and returns value
  3887. * that will appear in resulting Observable instead of default array.
  3888. * @return {Observable} Observable emitting either an array of last values emitted by passed Observables
  3889. * or value from project function.
  3890. * @static true
  3891. * @name forkJoin
  3892. * @owner Observable
  3893. */
  3894. ForkJoinObservable.create = function () {
  3895. var sources = [];
  3896. for (var _i = 0; _i < arguments.length; _i++) {
  3897. sources[_i - 0] = arguments[_i];
  3898. }
  3899. if (sources === null || arguments.length === 0) {
  3900. return new EmptyObservable();
  3901. }
  3902. var resultSelector = null;
  3903. if (typeof sources[sources.length - 1] === 'function') {
  3904. resultSelector = sources.pop();
  3905. }
  3906. // if the first and only other argument besides the resultSelector is an array
  3907. // assume it's been called with `forkJoin([obs1, obs2, obs3], resultSelector)`
  3908. if (sources.length === 1 && isArray(sources[0])) {
  3909. sources = sources[0];
  3910. }
  3911. if (sources.length === 0) {
  3912. return new EmptyObservable();
  3913. }
  3914. return new ForkJoinObservable(sources, resultSelector);
  3915. };
  3916. /** @deprecated internal use only */ ForkJoinObservable.prototype._subscribe = function (subscriber) {
  3917. return new ForkJoinSubscriber(subscriber, this.sources, this.resultSelector);
  3918. };
  3919. return ForkJoinObservable;
  3920. }(Observable));
  3921. /**
  3922. * We need this JSDoc comment for affecting ESDoc.
  3923. * @ignore
  3924. * @extends {Ignored}
  3925. */
  3926. var ForkJoinSubscriber = (function (_super) {
  3927. __extends(ForkJoinSubscriber, _super);
  3928. function ForkJoinSubscriber(destination, sources, resultSelector) {
  3929. _super.call(this, destination);
  3930. this.sources = sources;
  3931. this.resultSelector = resultSelector;
  3932. this.completed = 0;
  3933. this.haveValues = 0;
  3934. var len = sources.length;
  3935. this.total = len;
  3936. this.values = new Array(len);
  3937. for (var i = 0; i < len; i++) {
  3938. var source = sources[i];
  3939. var innerSubscription = subscribeToResult(this, source, null, i);
  3940. if (innerSubscription) {
  3941. innerSubscription.outerIndex = i;
  3942. this.add(innerSubscription);
  3943. }
  3944. }
  3945. }
  3946. ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  3947. this.values[outerIndex] = innerValue;
  3948. if (!innerSub._hasValue) {
  3949. innerSub._hasValue = true;
  3950. this.haveValues++;
  3951. }
  3952. };
  3953. ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) {
  3954. var destination = this.destination;
  3955. var _a = this, haveValues = _a.haveValues, resultSelector = _a.resultSelector, values = _a.values;
  3956. var len = values.length;
  3957. if (!innerSub._hasValue) {
  3958. destination.complete();
  3959. return;
  3960. }
  3961. this.completed++;
  3962. if (this.completed !== len) {
  3963. return;
  3964. }
  3965. if (haveValues === len) {
  3966. var value = resultSelector ? resultSelector.apply(this, values) : values;
  3967. destination.next(value);
  3968. }
  3969. destination.complete();
  3970. };
  3971. return ForkJoinSubscriber;
  3972. }(OuterSubscriber));
  3973. var forkJoin = ForkJoinObservable.create;
  3974. Observable.forkJoin = forkJoin;
  3975. Observable.from = from;
  3976. var toString = Object.prototype.toString;
  3977. function isNodeStyleEventEmitter(sourceObj) {
  3978. return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
  3979. }
  3980. function isJQueryStyleEventEmitter(sourceObj) {
  3981. return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
  3982. }
  3983. function isNodeList(sourceObj) {
  3984. return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
  3985. }
  3986. function isHTMLCollection(sourceObj) {
  3987. return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
  3988. }
  3989. function isEventTarget(sourceObj) {
  3990. return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
  3991. }
  3992. /**
  3993. * We need this JSDoc comment for affecting ESDoc.
  3994. * @extends {Ignored}
  3995. * @hide true
  3996. */
  3997. var FromEventObservable = (function (_super) {
  3998. __extends(FromEventObservable, _super);
  3999. function FromEventObservable(sourceObj, eventName, selector, options) {
  4000. _super.call(this);
  4001. this.sourceObj = sourceObj;
  4002. this.eventName = eventName;
  4003. this.selector = selector;
  4004. this.options = options;
  4005. }
  4006. /* tslint:enable:max-line-length */
  4007. /**
  4008. * Creates an Observable that emits events of a specific type coming from the
  4009. * given event target.
  4010. *
  4011. * <span class="informal">Creates an Observable from DOM events, or Node.js
  4012. * EventEmitter events or others.</span>
  4013. *
  4014. * <img src="./img/fromEvent.png" width="100%">
  4015. *
  4016. * `fromEvent` accepts as a first argument event target, which is an object with methods
  4017. * for registering event handler functions. As a second argument it takes string that indicates
  4018. * type of event we want to listen for. `fromEvent` supports selected types of event targets,
  4019. * which are described in detail below. If your event target does not match any of the ones listed,
  4020. * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
  4021. * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
  4022. * handler functions have different names, but they all accept a string describing event type
  4023. * and function itself, which will be called whenever said event happens.
  4024. *
  4025. * Every time resulting Observable is subscribed, event handler function will be registered
  4026. * to event target on given event type. When that event fires, value
  4027. * passed as a first argument to registered function will be emitted by output Observable.
  4028. * When Observable is unsubscribed, function will be unregistered from event target.
  4029. *
  4030. * Note that if event target calls registered function with more than one argument, second
  4031. * and following arguments will not appear in resulting stream. In order to get access to them,
  4032. * you can pass to `fromEvent` optional project function, which will be called with all arguments
  4033. * passed to event handler. Output Observable will then emit value returned by project function,
  4034. * instead of the usual value.
  4035. *
  4036. * Remember that event targets listed below are checked via duck typing. It means that
  4037. * no matter what kind of object you have and no matter what environment you work in,
  4038. * you can safely use `fromEvent` on that object if it exposes described methods (provided
  4039. * of course they behave as was described above). So for example if Node.js library exposes
  4040. * event target which has the same method names as DOM EventTarget, `fromEvent` is still
  4041. * a good choice.
  4042. *
  4043. * If the API you use is more callback then event handler oriented (subscribed
  4044. * callback function fires only once and thus there is no need to manually
  4045. * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
  4046. * instead.
  4047. *
  4048. * `fromEvent` supports following types of event targets:
  4049. *
  4050. * **DOM EventTarget**
  4051. *
  4052. * This is an object with `addEventListener` and `removeEventListener` methods.
  4053. *
  4054. * In the browser, `addEventListener` accepts - apart from event type string and event
  4055. * handler function arguments - optional third parameter, which is either an object or boolean,
  4056. * both used for additional configuration how and when passed function will be called. When
  4057. * `fromEvent` is used with event target of that type, you can provide this values
  4058. * as third parameter as well.
  4059. *
  4060. * **Node.js EventEmitter**
  4061. *
  4062. * An object with `addListener` and `removeListener` methods.
  4063. *
  4064. * **JQuery-style event target**
  4065. *
  4066. * An object with `on` and `off` methods
  4067. *
  4068. * **DOM NodeList**
  4069. *
  4070. * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
  4071. *
  4072. * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
  4073. * it contains and install event handler function in every of them. When returned Observable
  4074. * is unsubscribed, function will be removed from all Nodes.
  4075. *
  4076. * **DOM HtmlCollection**
  4077. *
  4078. * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
  4079. * installed and removed in each of elements.
  4080. *
  4081. *
  4082. * @example <caption>Emits clicks happening on the DOM document</caption>
  4083. * var clicks = Rx.Observable.fromEvent(document, 'click');
  4084. * clicks.subscribe(x => console.log(x));
  4085. *
  4086. * // Results in:
  4087. * // MouseEvent object logged to console every time a click
  4088. * // occurs on the document.
  4089. *
  4090. *
  4091. * @example <caption>Use addEventListener with capture option</caption>
  4092. * var clicksInDocument = Rx.Observable.fromEvent(document, 'click', true); // note optional configuration parameter
  4093. * // which will be passed to addEventListener
  4094. * var clicksInDiv = Rx.Observable.fromEvent(someDivInDocument, 'click');
  4095. *
  4096. * clicksInDocument.subscribe(() => console.log('document'));
  4097. * clicksInDiv.subscribe(() => console.log('div'));
  4098. *
  4099. * // By default events bubble UP in DOM tree, so normally
  4100. * // when we would click on div in document
  4101. * // "div" would be logged first and then "document".
  4102. * // Since we specified optional `capture` option, document
  4103. * // will catch event when it goes DOWN DOM tree, so console
  4104. * // will log "document" and then "div".
  4105. *
  4106. * @see {@link bindCallback}
  4107. * @see {@link bindNodeCallback}
  4108. * @see {@link fromEventPattern}
  4109. *
  4110. * @param {EventTargetLike} target The DOM EventTarget, Node.js
  4111. * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.
  4112. * @param {string} eventName The event name of interest, being emitted by the
  4113. * `target`.
  4114. * @param {EventListenerOptions} [options] Options to pass through to addEventListener
  4115. * @param {SelectorMethodSignature<T>} [selector] An optional function to
  4116. * post-process results. It takes the arguments from the event handler and
  4117. * should return a single value.
  4118. * @return {Observable<T>}
  4119. * @static true
  4120. * @name fromEvent
  4121. * @owner Observable
  4122. */
  4123. FromEventObservable.create = function (target, eventName, options, selector) {
  4124. if (isFunction(options)) {
  4125. selector = options;
  4126. options = undefined;
  4127. }
  4128. return new FromEventObservable(target, eventName, selector, options);
  4129. };
  4130. FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
  4131. var unsubscribe;
  4132. if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
  4133. for (var i = 0, len = sourceObj.length; i < len; i++) {
  4134. FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
  4135. }
  4136. }
  4137. else if (isEventTarget(sourceObj)) {
  4138. var source_1 = sourceObj;
  4139. sourceObj.addEventListener(eventName, handler, options);
  4140. unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };
  4141. }
  4142. else if (isJQueryStyleEventEmitter(sourceObj)) {
  4143. var source_2 = sourceObj;
  4144. sourceObj.on(eventName, handler);
  4145. unsubscribe = function () { return source_2.off(eventName, handler); };
  4146. }
  4147. else if (isNodeStyleEventEmitter(sourceObj)) {
  4148. var source_3 = sourceObj;
  4149. sourceObj.addListener(eventName, handler);
  4150. unsubscribe = function () { return source_3.removeListener(eventName, handler); };
  4151. }
  4152. else {
  4153. throw new TypeError('Invalid event target');
  4154. }
  4155. subscriber.add(new Subscription(unsubscribe));
  4156. };
  4157. /** @deprecated internal use only */ FromEventObservable.prototype._subscribe = function (subscriber) {
  4158. var sourceObj = this.sourceObj;
  4159. var eventName = this.eventName;
  4160. var options = this.options;
  4161. var selector = this.selector;
  4162. var handler = selector ? function () {
  4163. var args = [];
  4164. for (var _i = 0; _i < arguments.length; _i++) {
  4165. args[_i - 0] = arguments[_i];
  4166. }
  4167. var result = tryCatch(selector).apply(void 0, args);
  4168. if (result === errorObject) {
  4169. subscriber.error(errorObject.e);
  4170. }
  4171. else {
  4172. subscriber.next(result);
  4173. }
  4174. } : function (e) { return subscriber.next(e); };
  4175. FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
  4176. };
  4177. return FromEventObservable;
  4178. }(Observable));
  4179. var fromEvent = FromEventObservable.create;
  4180. Observable.fromEvent = fromEvent;
  4181. /**
  4182. * We need this JSDoc comment for affecting ESDoc.
  4183. * @extends {Ignored}
  4184. * @hide true
  4185. */
  4186. var FromEventPatternObservable = (function (_super) {
  4187. __extends(FromEventPatternObservable, _super);
  4188. function FromEventPatternObservable(addHandler, removeHandler, selector) {
  4189. _super.call(this);
  4190. this.addHandler = addHandler;
  4191. this.removeHandler = removeHandler;
  4192. this.selector = selector;
  4193. }
  4194. /**
  4195. * Creates an Observable from an API based on addHandler/removeHandler
  4196. * functions.
  4197. *
  4198. * <span class="informal">Converts any addHandler/removeHandler API to an
  4199. * Observable.</span>
  4200. *
  4201. * <img src="./img/fromEventPattern.png" width="100%">
  4202. *
  4203. * Creates an Observable by using the `addHandler` and `removeHandler`
  4204. * functions to add and remove the handlers, with an optional selector
  4205. * function to project the event arguments to a result. The `addHandler` is
  4206. * called when the output Observable is subscribed, and `removeHandler` is
  4207. * called when the Subscription is unsubscribed.
  4208. *
  4209. * @example <caption>Emits clicks happening on the DOM document</caption>
  4210. * function addClickHandler(handler) {
  4211. * document.addEventListener('click', handler);
  4212. * }
  4213. *
  4214. * function removeClickHandler(handler) {
  4215. * document.removeEventListener('click', handler);
  4216. * }
  4217. *
  4218. * var clicks = Rx.Observable.fromEventPattern(
  4219. * addClickHandler,
  4220. * removeClickHandler
  4221. * );
  4222. * clicks.subscribe(x => console.log(x));
  4223. *
  4224. * @see {@link from}
  4225. * @see {@link fromEvent}
  4226. *
  4227. * @param {function(handler: Function): any} addHandler A function that takes
  4228. * a `handler` function as argument and attaches it somehow to the actual
  4229. * source of events.
  4230. * @param {function(handler: Function, signal?: any): void} [removeHandler] An optional function that
  4231. * takes a `handler` function as argument and removes it in case it was
  4232. * previously attached using `addHandler`. if addHandler returns signal to teardown when remove,
  4233. * removeHandler function will forward it.
  4234. * @param {function(...args: any): T} [selector] An optional function to
  4235. * post-process results. It takes the arguments from the event handler and
  4236. * should return a single value.
  4237. * @return {Observable<T>}
  4238. * @static true
  4239. * @name fromEventPattern
  4240. * @owner Observable
  4241. */
  4242. FromEventPatternObservable.create = function (addHandler, removeHandler, selector) {
  4243. return new FromEventPatternObservable(addHandler, removeHandler, selector);
  4244. };
  4245. /** @deprecated internal use only */ FromEventPatternObservable.prototype._subscribe = function (subscriber) {
  4246. var _this = this;
  4247. var removeHandler = this.removeHandler;
  4248. var handler = !!this.selector ? function () {
  4249. var args = [];
  4250. for (var _i = 0; _i < arguments.length; _i++) {
  4251. args[_i - 0] = arguments[_i];
  4252. }
  4253. _this._callSelector(subscriber, args);
  4254. } : function (e) { subscriber.next(e); };
  4255. var retValue = this._callAddHandler(handler, subscriber);
  4256. if (!isFunction(removeHandler)) {
  4257. return;
  4258. }
  4259. subscriber.add(new Subscription(function () {
  4260. //TODO: determine whether or not to forward to error handler
  4261. removeHandler(handler, retValue);
  4262. }));
  4263. };
  4264. FromEventPatternObservable.prototype._callSelector = function (subscriber, args) {
  4265. try {
  4266. var result = this.selector.apply(this, args);
  4267. subscriber.next(result);
  4268. }
  4269. catch (e) {
  4270. subscriber.error(e);
  4271. }
  4272. };
  4273. FromEventPatternObservable.prototype._callAddHandler = function (handler, errorSubscriber) {
  4274. try {
  4275. return this.addHandler(handler) || null;
  4276. }
  4277. catch (e) {
  4278. errorSubscriber.error(e);
  4279. }
  4280. };
  4281. return FromEventPatternObservable;
  4282. }(Observable));
  4283. var fromEventPattern = FromEventPatternObservable.create;
  4284. Observable.fromEventPattern = fromEventPattern;
  4285. var fromPromise = PromiseObservable.create;
  4286. Observable.fromPromise = fromPromise;
  4287. var selfSelector = function (value) { return value; };
  4288. /**
  4289. * We need this JSDoc comment for affecting ESDoc.
  4290. * @extends {Ignored}
  4291. * @hide true
  4292. */
  4293. var GenerateObservable = (function (_super) {
  4294. __extends(GenerateObservable, _super);
  4295. function GenerateObservable(initialState, condition, iterate, resultSelector, scheduler) {
  4296. _super.call(this);
  4297. this.initialState = initialState;
  4298. this.condition = condition;
  4299. this.iterate = iterate;
  4300. this.resultSelector = resultSelector;
  4301. this.scheduler = scheduler;
  4302. }
  4303. GenerateObservable.create = function (initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) {
  4304. if (arguments.length == 1) {
  4305. return new GenerateObservable(initialStateOrOptions.initialState, initialStateOrOptions.condition, initialStateOrOptions.iterate, initialStateOrOptions.resultSelector || selfSelector, initialStateOrOptions.scheduler);
  4306. }
  4307. if (resultSelectorOrObservable === undefined || isScheduler(resultSelectorOrObservable)) {
  4308. return new GenerateObservable(initialStateOrOptions, condition, iterate, selfSelector, resultSelectorOrObservable);
  4309. }
  4310. return new GenerateObservable(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler);
  4311. };
  4312. /** @deprecated internal use only */ GenerateObservable.prototype._subscribe = function (subscriber) {
  4313. var state = this.initialState;
  4314. if (this.scheduler) {
  4315. return this.scheduler.schedule(GenerateObservable.dispatch, 0, {
  4316. subscriber: subscriber,
  4317. iterate: this.iterate,
  4318. condition: this.condition,
  4319. resultSelector: this.resultSelector,
  4320. state: state });
  4321. }
  4322. var _a = this, condition = _a.condition, resultSelector = _a.resultSelector, iterate = _a.iterate;
  4323. do {
  4324. if (condition) {
  4325. var conditionResult = void 0;
  4326. try {
  4327. conditionResult = condition(state);
  4328. }
  4329. catch (err) {
  4330. subscriber.error(err);
  4331. return;
  4332. }
  4333. if (!conditionResult) {
  4334. subscriber.complete();
  4335. break;
  4336. }
  4337. }
  4338. var value = void 0;
  4339. try {
  4340. value = resultSelector(state);
  4341. }
  4342. catch (err) {
  4343. subscriber.error(err);
  4344. return;
  4345. }
  4346. subscriber.next(value);
  4347. if (subscriber.closed) {
  4348. break;
  4349. }
  4350. try {
  4351. state = iterate(state);
  4352. }
  4353. catch (err) {
  4354. subscriber.error(err);
  4355. return;
  4356. }
  4357. } while (true);
  4358. };
  4359. GenerateObservable.dispatch = function (state) {
  4360. var subscriber = state.subscriber, condition = state.condition;
  4361. if (subscriber.closed) {
  4362. return;
  4363. }
  4364. if (state.needIterate) {
  4365. try {
  4366. state.state = state.iterate(state.state);
  4367. }
  4368. catch (err) {
  4369. subscriber.error(err);
  4370. return;
  4371. }
  4372. }
  4373. else {
  4374. state.needIterate = true;
  4375. }
  4376. if (condition) {
  4377. var conditionResult = void 0;
  4378. try {
  4379. conditionResult = condition(state.state);
  4380. }
  4381. catch (err) {
  4382. subscriber.error(err);
  4383. return;
  4384. }
  4385. if (!conditionResult) {
  4386. subscriber.complete();
  4387. return;
  4388. }
  4389. if (subscriber.closed) {
  4390. return;
  4391. }
  4392. }
  4393. var value;
  4394. try {
  4395. value = state.resultSelector(state.state);
  4396. }
  4397. catch (err) {
  4398. subscriber.error(err);
  4399. return;
  4400. }
  4401. if (subscriber.closed) {
  4402. return;
  4403. }
  4404. subscriber.next(value);
  4405. if (subscriber.closed) {
  4406. return;
  4407. }
  4408. return this.schedule(state);
  4409. };
  4410. return GenerateObservable;
  4411. }(Observable));
  4412. var generate = GenerateObservable.create;
  4413. Observable.generate = generate;
  4414. /**
  4415. * We need this JSDoc comment for affecting ESDoc.
  4416. * @extends {Ignored}
  4417. * @hide true
  4418. */
  4419. var IfObservable = (function (_super) {
  4420. __extends(IfObservable, _super);
  4421. function IfObservable(condition, thenSource, elseSource) {
  4422. _super.call(this);
  4423. this.condition = condition;
  4424. this.thenSource = thenSource;
  4425. this.elseSource = elseSource;
  4426. }
  4427. IfObservable.create = function (condition, thenSource, elseSource) {
  4428. return new IfObservable(condition, thenSource, elseSource);
  4429. };
  4430. /** @deprecated internal use only */ IfObservable.prototype._subscribe = function (subscriber) {
  4431. var _a = this, condition = _a.condition, thenSource = _a.thenSource, elseSource = _a.elseSource;
  4432. return new IfSubscriber(subscriber, condition, thenSource, elseSource);
  4433. };
  4434. return IfObservable;
  4435. }(Observable));
  4436. var IfSubscriber = (function (_super) {
  4437. __extends(IfSubscriber, _super);
  4438. function IfSubscriber(destination, condition, thenSource, elseSource) {
  4439. _super.call(this, destination);
  4440. this.condition = condition;
  4441. this.thenSource = thenSource;
  4442. this.elseSource = elseSource;
  4443. this.tryIf();
  4444. }
  4445. IfSubscriber.prototype.tryIf = function () {
  4446. var _a = this, condition = _a.condition, thenSource = _a.thenSource, elseSource = _a.elseSource;
  4447. var result;
  4448. try {
  4449. result = condition();
  4450. var source = result ? thenSource : elseSource;
  4451. if (source) {
  4452. this.add(subscribeToResult(this, source));
  4453. }
  4454. else {
  4455. this._complete();
  4456. }
  4457. }
  4458. catch (err) {
  4459. this._error(err);
  4460. }
  4461. };
  4462. return IfSubscriber;
  4463. }(OuterSubscriber));
  4464. var _if = IfObservable.create;
  4465. Observable.if = _if;
  4466. function isNumeric(val) {
  4467. // parseFloat NaNs numeric-cast false positives (null|true|false|"")
  4468. // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  4469. // subtraction forces infinities to NaN
  4470. // adding 1 corrects loss of precision from parseFloat (#15100)
  4471. return !isArray(val) && (val - parseFloat(val) + 1) >= 0;
  4472. }
  4473. /**
  4474. * A unit of work to be executed in a {@link Scheduler}. An action is typically
  4475. * created from within a Scheduler and an RxJS user does not need to concern
  4476. * themselves about creating and manipulating an Action.
  4477. *
  4478. * ```ts
  4479. * class Action<T> extends Subscription {
  4480. * new (scheduler: Scheduler, work: (state?: T) => void);
  4481. * schedule(state?: T, delay: number = 0): Subscription;
  4482. * }
  4483. * ```
  4484. *
  4485. * @class Action<T>
  4486. */
  4487. var Action = (function (_super) {
  4488. __extends(Action, _super);
  4489. function Action(scheduler, work) {
  4490. _super.call(this);
  4491. }
  4492. /**
  4493. * Schedules this action on its parent Scheduler for execution. May be passed
  4494. * some context object, `state`. May happen at some point in the future,
  4495. * according to the `delay` parameter, if specified.
  4496. * @param {T} [state] Some contextual data that the `work` function uses when
  4497. * called by the Scheduler.
  4498. * @param {number} [delay] Time to wait before executing the work, where the
  4499. * time unit is implicit and defined by the Scheduler.
  4500. * @return {void}
  4501. */
  4502. Action.prototype.schedule = function (state, delay) {
  4503. if (delay === void 0) { delay = 0; }
  4504. return this;
  4505. };
  4506. return Action;
  4507. }(Subscription));
  4508. /**
  4509. * We need this JSDoc comment for affecting ESDoc.
  4510. * @ignore
  4511. * @extends {Ignored}
  4512. */
  4513. var AsyncAction = (function (_super) {
  4514. __extends(AsyncAction, _super);
  4515. function AsyncAction(scheduler, work) {
  4516. _super.call(this, scheduler, work);
  4517. this.scheduler = scheduler;
  4518. this.pending = false;
  4519. this.work = work;
  4520. }
  4521. AsyncAction.prototype.schedule = function (state, delay) {
  4522. if (delay === void 0) { delay = 0; }
  4523. if (this.closed) {
  4524. return this;
  4525. }
  4526. // Always replace the current state with the new state.
  4527. this.state = state;
  4528. // Set the pending flag indicating that this action has been scheduled, or
  4529. // has recursively rescheduled itself.
  4530. this.pending = true;
  4531. var id = this.id;
  4532. var scheduler = this.scheduler;
  4533. //
  4534. // Important implementation note:
  4535. //
  4536. // Actions only execute once by default, unless rescheduled from within the
  4537. // scheduled callback. This allows us to implement single and repeat
  4538. // actions via the same code path, without adding API surface area, as well
  4539. // as mimic traditional recursion but across asynchronous boundaries.
  4540. //
  4541. // However, JS runtimes and timers distinguish between intervals achieved by
  4542. // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
  4543. // serial `setTimeout` calls can be individually delayed, which delays
  4544. // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
  4545. // guarantee the interval callback will be invoked more precisely to the
  4546. // interval period, regardless of load.
  4547. //
  4548. // Therefore, we use `setInterval` to schedule single and repeat actions.
  4549. // If the action reschedules itself with the same delay, the interval is not
  4550. // canceled. If the action doesn't reschedule, or reschedules with a
  4551. // different delay, the interval will be canceled after scheduled callback
  4552. // execution.
  4553. //
  4554. if (id != null) {
  4555. this.id = this.recycleAsyncId(scheduler, id, delay);
  4556. }
  4557. this.delay = delay;
  4558. // If this action has already an async Id, don't request a new one.
  4559. this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
  4560. return this;
  4561. };
  4562. AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
  4563. if (delay === void 0) { delay = 0; }
  4564. return _root.setInterval(scheduler.flush.bind(scheduler, this), delay);
  4565. };
  4566. AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
  4567. if (delay === void 0) { delay = 0; }
  4568. // If this action is rescheduled with the same delay time, don't clear the interval id.
  4569. if (delay !== null && this.delay === delay && this.pending === false) {
  4570. return id;
  4571. }
  4572. // Otherwise, if the action's delay time is different from the current delay,
  4573. // or the action has been rescheduled before it's executed, clear the interval id
  4574. return _root.clearInterval(id) && undefined || undefined;
  4575. };
  4576. /**
  4577. * Immediately executes this action and the `work` it contains.
  4578. * @return {any}
  4579. */
  4580. AsyncAction.prototype.execute = function (state, delay) {
  4581. if (this.closed) {
  4582. return new Error('executing a cancelled action');
  4583. }
  4584. this.pending = false;
  4585. var error = this._execute(state, delay);
  4586. if (error) {
  4587. return error;
  4588. }
  4589. else if (this.pending === false && this.id != null) {
  4590. // Dequeue if the action didn't reschedule itself. Don't call
  4591. // unsubscribe(), because the action could reschedule later.
  4592. // For example:
  4593. // ```
  4594. // scheduler.schedule(function doWork(counter) {
  4595. // /* ... I'm a busy worker bee ... */
  4596. // var originalAction = this;
  4597. // /* wait 100ms before rescheduling the action */
  4598. // setTimeout(function () {
  4599. // originalAction.schedule(counter + 1);
  4600. // }, 100);
  4601. // }, 1000);
  4602. // ```
  4603. this.id = this.recycleAsyncId(this.scheduler, this.id, null);
  4604. }
  4605. };
  4606. AsyncAction.prototype._execute = function (state, delay) {
  4607. var errored = false;
  4608. var errorValue = undefined;
  4609. try {
  4610. this.work(state);
  4611. }
  4612. catch (e) {
  4613. errored = true;
  4614. errorValue = !!e && e || new Error(e);
  4615. }
  4616. if (errored) {
  4617. this.unsubscribe();
  4618. return errorValue;
  4619. }
  4620. };
  4621. /** @deprecated internal use only */ AsyncAction.prototype._unsubscribe = function () {
  4622. var id = this.id;
  4623. var scheduler = this.scheduler;
  4624. var actions = scheduler.actions;
  4625. var index = actions.indexOf(this);
  4626. this.work = null;
  4627. this.state = null;
  4628. this.pending = false;
  4629. this.scheduler = null;
  4630. if (index !== -1) {
  4631. actions.splice(index, 1);
  4632. }
  4633. if (id != null) {
  4634. this.id = this.recycleAsyncId(scheduler, id, null);
  4635. }
  4636. this.delay = null;
  4637. };
  4638. return AsyncAction;
  4639. }(Action));
  4640. /**
  4641. * An execution context and a data structure to order tasks and schedule their
  4642. * execution. Provides a notion of (potentially virtual) time, through the
  4643. * `now()` getter method.
  4644. *
  4645. * Each unit of work in a Scheduler is called an {@link Action}.
  4646. *
  4647. * ```ts
  4648. * class Scheduler {
  4649. * now(): number;
  4650. * schedule(work, delay?, state?): Subscription;
  4651. * }
  4652. * ```
  4653. *
  4654. * @class Scheduler
  4655. */
  4656. var Scheduler$1 = (function () {
  4657. function Scheduler(SchedulerAction, now) {
  4658. if (now === void 0) { now = Scheduler.now; }
  4659. this.SchedulerAction = SchedulerAction;
  4660. this.now = now;
  4661. }
  4662. /**
  4663. * Schedules a function, `work`, for execution. May happen at some point in
  4664. * the future, according to the `delay` parameter, if specified. May be passed
  4665. * some context object, `state`, which will be passed to the `work` function.
  4666. *
  4667. * The given arguments will be processed an stored as an Action object in a
  4668. * queue of actions.
  4669. *
  4670. * @param {function(state: ?T): ?Subscription} work A function representing a
  4671. * task, or some unit of work to be executed by the Scheduler.
  4672. * @param {number} [delay] Time to wait before executing the work, where the
  4673. * time unit is implicit and defined by the Scheduler itself.
  4674. * @param {T} [state] Some contextual data that the `work` function uses when
  4675. * called by the Scheduler.
  4676. * @return {Subscription} A subscription in order to be able to unsubscribe
  4677. * the scheduled work.
  4678. */
  4679. Scheduler.prototype.schedule = function (work, delay, state) {
  4680. if (delay === void 0) { delay = 0; }
  4681. return new this.SchedulerAction(this, work).schedule(state, delay);
  4682. };
  4683. Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
  4684. return Scheduler;
  4685. }());
  4686. var AsyncScheduler = (function (_super) {
  4687. __extends(AsyncScheduler, _super);
  4688. function AsyncScheduler() {
  4689. _super.apply(this, arguments);
  4690. this.actions = [];
  4691. /**
  4692. * A flag to indicate whether the Scheduler is currently executing a batch of
  4693. * queued actions.
  4694. * @type {boolean}
  4695. */
  4696. this.active = false;
  4697. /**
  4698. * An internal ID used to track the latest asynchronous task such as those
  4699. * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
  4700. * others.
  4701. * @type {any}
  4702. */
  4703. this.scheduled = undefined;
  4704. }
  4705. AsyncScheduler.prototype.flush = function (action) {
  4706. var actions = this.actions;
  4707. if (this.active) {
  4708. actions.push(action);
  4709. return;
  4710. }
  4711. var error;
  4712. this.active = true;
  4713. do {
  4714. if (error = action.execute(action.state, action.delay)) {
  4715. break;
  4716. }
  4717. } while (action = actions.shift()); // exhaust the scheduler queue
  4718. this.active = false;
  4719. if (error) {
  4720. while (action = actions.shift()) {
  4721. action.unsubscribe();
  4722. }
  4723. throw error;
  4724. }
  4725. };
  4726. return AsyncScheduler;
  4727. }(Scheduler$1));
  4728. /**
  4729. *
  4730. * Async Scheduler
  4731. *
  4732. * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
  4733. *
  4734. * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
  4735. * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
  4736. * in intervals.
  4737. *
  4738. * If you just want to "defer" task, that is to perform it right after currently
  4739. * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
  4740. * better choice will be the {@link asap} scheduler.
  4741. *
  4742. * @example <caption>Use async scheduler to delay task</caption>
  4743. * const task = () => console.log('it works!');
  4744. *
  4745. * Rx.Scheduler.async.schedule(task, 2000);
  4746. *
  4747. * // After 2 seconds logs:
  4748. * // "it works!"
  4749. *
  4750. *
  4751. * @example <caption>Use async scheduler to repeat task in intervals</caption>
  4752. * function task(state) {
  4753. * console.log(state);
  4754. * this.schedule(state + 1, 1000); // `this` references currently executing Action,
  4755. * // which we reschedule with new state and delay
  4756. * }
  4757. *
  4758. * Rx.Scheduler.async.schedule(task, 3000, 0);
  4759. *
  4760. * // Logs:
  4761. * // 0 after 3s
  4762. * // 1 after 4s
  4763. * // 2 after 5s
  4764. * // 3 after 6s
  4765. *
  4766. * @static true
  4767. * @name async
  4768. * @owner Scheduler
  4769. */
  4770. var async = new AsyncScheduler(AsyncAction);
  4771. /**
  4772. * We need this JSDoc comment for affecting ESDoc.
  4773. * @extends {Ignored}
  4774. * @hide true
  4775. */
  4776. var IntervalObservable = (function (_super) {
  4777. __extends(IntervalObservable, _super);
  4778. function IntervalObservable(period, scheduler) {
  4779. if (period === void 0) { period = 0; }
  4780. if (scheduler === void 0) { scheduler = async; }
  4781. _super.call(this);
  4782. this.period = period;
  4783. this.scheduler = scheduler;
  4784. if (!isNumeric(period) || period < 0) {
  4785. this.period = 0;
  4786. }
  4787. if (!scheduler || typeof scheduler.schedule !== 'function') {
  4788. this.scheduler = async;
  4789. }
  4790. }
  4791. /**
  4792. * Creates an Observable that emits sequential numbers every specified
  4793. * interval of time, on a specified IScheduler.
  4794. *
  4795. * <span class="informal">Emits incremental numbers periodically in time.
  4796. * </span>
  4797. *
  4798. * <img src="./img/interval.png" width="100%">
  4799. *
  4800. * `interval` returns an Observable that emits an infinite sequence of
  4801. * ascending integers, with a constant interval of time of your choosing
  4802. * between those emissions. The first emission is not sent immediately, but
  4803. * only after the first period has passed. By default, this operator uses the
  4804. * `async` IScheduler to provide a notion of time, but you may pass any
  4805. * IScheduler to it.
  4806. *
  4807. * @example <caption>Emits ascending numbers, one every second (1000ms)</caption>
  4808. * var numbers = Rx.Observable.interval(1000);
  4809. * numbers.subscribe(x => console.log(x));
  4810. *
  4811. * @see {@link timer}
  4812. * @see {@link delay}
  4813. *
  4814. * @param {number} [period=0] The interval size in milliseconds (by default)
  4815. * or the time unit determined by the scheduler's clock.
  4816. * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
  4817. * the emission of values, and providing a notion of "time".
  4818. * @return {Observable} An Observable that emits a sequential number each time
  4819. * interval.
  4820. * @static true
  4821. * @name interval
  4822. * @owner Observable
  4823. */
  4824. IntervalObservable.create = function (period, scheduler) {
  4825. if (period === void 0) { period = 0; }
  4826. if (scheduler === void 0) { scheduler = async; }
  4827. return new IntervalObservable(period, scheduler);
  4828. };
  4829. IntervalObservable.dispatch = function (state) {
  4830. var index = state.index, subscriber = state.subscriber, period = state.period;
  4831. subscriber.next(index);
  4832. if (subscriber.closed) {
  4833. return;
  4834. }
  4835. state.index += 1;
  4836. this.schedule(state, period);
  4837. };
  4838. /** @deprecated internal use only */ IntervalObservable.prototype._subscribe = function (subscriber) {
  4839. var index = 0;
  4840. var period = this.period;
  4841. var scheduler = this.scheduler;
  4842. subscriber.add(scheduler.schedule(IntervalObservable.dispatch, period, {
  4843. index: index, subscriber: subscriber, period: period
  4844. }));
  4845. };
  4846. return IntervalObservable;
  4847. }(Observable));
  4848. var interval = IntervalObservable.create;
  4849. Observable.interval = interval;
  4850. /* tslint:enable:max-line-length */
  4851. /**
  4852. * Creates an output Observable which concurrently emits all values from every
  4853. * given input Observable.
  4854. *
  4855. * <span class="informal">Flattens multiple Observables together by blending
  4856. * their values into one Observable.</span>
  4857. *
  4858. * <img src="./img/merge.png" width="100%">
  4859. *
  4860. * `merge` subscribes to each given input Observable (as arguments), and simply
  4861. * forwards (without doing any transformation) all the values from all the input
  4862. * Observables to the output Observable. The output Observable only completes
  4863. * once all input Observables have completed. Any error delivered by an input
  4864. * Observable will be immediately emitted on the output Observable.
  4865. *
  4866. * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
  4867. * var clicks = Rx.Observable.fromEvent(document, 'click');
  4868. * var timer = Rx.Observable.interval(1000);
  4869. * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
  4870. * clicksOrTimer.subscribe(x => console.log(x));
  4871. *
  4872. * // Results in the following:
  4873. * // timer will emit ascending values, one every second(1000ms) to console
  4874. * // clicks logs MouseEvents to console everytime the "document" is clicked
  4875. * // Since the two streams are merged you see these happening
  4876. * // as they occur.
  4877. *
  4878. * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
  4879. * var timer1 = Rx.Observable.interval(1000).take(10);
  4880. * var timer2 = Rx.Observable.interval(2000).take(6);
  4881. * var timer3 = Rx.Observable.interval(500).take(10);
  4882. * var concurrent = 2; // the argument
  4883. * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
  4884. * merged.subscribe(x => console.log(x));
  4885. *
  4886. * // Results in the following:
  4887. * // - First timer1 and timer2 will run concurrently
  4888. * // - timer1 will emit a value every 1000ms for 10 iterations
  4889. * // - timer2 will emit a value every 2000ms for 6 iterations
  4890. * // - after timer1 hits it's max iteration, timer2 will
  4891. * // continue, and timer3 will start to run concurrently with timer2
  4892. * // - when timer2 hits it's max iteration it terminates, and
  4893. * // timer3 will continue to emit a value every 500ms until it is complete
  4894. *
  4895. * @see {@link mergeAll}
  4896. * @see {@link mergeMap}
  4897. * @see {@link mergeMapTo}
  4898. * @see {@link mergeScan}
  4899. *
  4900. * @param {...ObservableInput} observables Input Observables to merge together.
  4901. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  4902. * Observables being subscribed to concurrently.
  4903. * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
  4904. * concurrency of input Observables.
  4905. * @return {Observable} an Observable that emits items that are the result of
  4906. * every input Observable.
  4907. * @static true
  4908. * @name merge
  4909. * @owner Observable
  4910. */
  4911. function merge() {
  4912. var observables = [];
  4913. for (var _i = 0; _i < arguments.length; _i++) {
  4914. observables[_i - 0] = arguments[_i];
  4915. }
  4916. var concurrent = Number.POSITIVE_INFINITY;
  4917. var scheduler = null;
  4918. var last = observables[observables.length - 1];
  4919. if (isScheduler(last)) {
  4920. scheduler = observables.pop();
  4921. if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
  4922. concurrent = observables.pop();
  4923. }
  4924. }
  4925. else if (typeof last === 'number') {
  4926. concurrent = observables.pop();
  4927. }
  4928. if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {
  4929. return observables[0];
  4930. }
  4931. return mergeAll(concurrent)(new ArrayObservable(observables, scheduler));
  4932. }
  4933. Observable.merge = merge;
  4934. function race() {
  4935. var observables = [];
  4936. for (var _i = 0; _i < arguments.length; _i++) {
  4937. observables[_i - 0] = arguments[_i];
  4938. }
  4939. // if the only argument is an array, it was most likely called with
  4940. // `race([obs1, obs2, ...])`
  4941. if (observables.length === 1) {
  4942. if (isArray(observables[0])) {
  4943. observables = observables[0];
  4944. }
  4945. else {
  4946. return observables[0];
  4947. }
  4948. }
  4949. return new ArrayObservable(observables).lift(new RaceOperator());
  4950. }
  4951. var RaceOperator = (function () {
  4952. function RaceOperator() {
  4953. }
  4954. RaceOperator.prototype.call = function (subscriber, source) {
  4955. return source.subscribe(new RaceSubscriber(subscriber));
  4956. };
  4957. return RaceOperator;
  4958. }());
  4959. /**
  4960. * We need this JSDoc comment for affecting ESDoc.
  4961. * @ignore
  4962. * @extends {Ignored}
  4963. */
  4964. var RaceSubscriber = (function (_super) {
  4965. __extends(RaceSubscriber, _super);
  4966. function RaceSubscriber(destination) {
  4967. _super.call(this, destination);
  4968. this.hasFirst = false;
  4969. this.observables = [];
  4970. this.subscriptions = [];
  4971. }
  4972. RaceSubscriber.prototype._next = function (observable) {
  4973. this.observables.push(observable);
  4974. };
  4975. RaceSubscriber.prototype._complete = function () {
  4976. var observables = this.observables;
  4977. var len = observables.length;
  4978. if (len === 0) {
  4979. this.destination.complete();
  4980. }
  4981. else {
  4982. for (var i = 0; i < len && !this.hasFirst; i++) {
  4983. var observable = observables[i];
  4984. var subscription = subscribeToResult(this, observable, observable, i);
  4985. if (this.subscriptions) {
  4986. this.subscriptions.push(subscription);
  4987. }
  4988. this.add(subscription);
  4989. }
  4990. this.observables = null;
  4991. }
  4992. };
  4993. RaceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  4994. if (!this.hasFirst) {
  4995. this.hasFirst = true;
  4996. for (var i = 0; i < this.subscriptions.length; i++) {
  4997. if (i !== outerIndex) {
  4998. var subscription = this.subscriptions[i];
  4999. subscription.unsubscribe();
  5000. this.remove(subscription);
  5001. }
  5002. }
  5003. this.subscriptions = null;
  5004. }
  5005. this.destination.next(innerValue);
  5006. };
  5007. return RaceSubscriber;
  5008. }(OuterSubscriber));
  5009. Observable.race = race;
  5010. /**
  5011. * We need this JSDoc comment for affecting ESDoc.
  5012. * @extends {Ignored}
  5013. * @hide true
  5014. */
  5015. var NeverObservable = (function (_super) {
  5016. __extends(NeverObservable, _super);
  5017. function NeverObservable() {
  5018. _super.call(this);
  5019. }
  5020. /**
  5021. * Creates an Observable that emits no items to the Observer.
  5022. *
  5023. * <span class="informal">An Observable that never emits anything.</span>
  5024. *
  5025. * <img src="./img/never.png" width="100%">
  5026. *
  5027. * This static operator is useful for creating a simple Observable that emits
  5028. * neither values nor errors nor the completion notification. It can be used
  5029. * for testing purposes or for composing with other Observables. Please note
  5030. * that by never emitting a complete notification, this Observable keeps the
  5031. * subscription from being disposed automatically. Subscriptions need to be
  5032. * manually disposed.
  5033. *
  5034. * @example <caption>Emit the number 7, then never emit anything else (not even complete).</caption>
  5035. * function info() {
  5036. * console.log('Will not be called');
  5037. * }
  5038. * var result = Rx.Observable.never().startWith(7);
  5039. * result.subscribe(x => console.log(x), info, info);
  5040. *
  5041. * @see {@link create}
  5042. * @see {@link empty}
  5043. * @see {@link of}
  5044. * @see {@link throw}
  5045. *
  5046. * @return {Observable} A "never" Observable: never emits anything.
  5047. * @static true
  5048. * @name never
  5049. * @owner Observable
  5050. */
  5051. NeverObservable.create = function () {
  5052. return new NeverObservable();
  5053. };
  5054. /** @deprecated internal use only */ NeverObservable.prototype._subscribe = function (subscriber) {
  5055. noop();
  5056. };
  5057. return NeverObservable;
  5058. }(Observable));
  5059. var never = NeverObservable.create;
  5060. Observable.never = never;
  5061. Observable.of = of;
  5062. /* tslint:enable:max-line-length */
  5063. /**
  5064. * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one
  5065. * that was passed.
  5066. *
  5067. * <span class="informal">Execute series of Observables no matter what, even if it means swallowing errors.</span>
  5068. *
  5069. * <img src="./img/onErrorResumeNext.png" width="100%">
  5070. *
  5071. * `onErrorResumeNext` is an operator that accepts a series of Observables, provided either directly as
  5072. * arguments or as an array. If no single Observable is provided, returned Observable will simply behave the same
  5073. * as the source.
  5074. *
  5075. * `onErrorResumeNext` returns an Observable that starts by subscribing and re-emitting values from the source Observable.
  5076. * When its stream of values ends - no matter if Observable completed or emitted an error - `onErrorResumeNext`
  5077. * will subscribe to the first Observable that was passed as an argument to the method. It will start re-emitting
  5078. * its values as well and - again - when that stream ends, `onErrorResumeNext` will proceed to subscribing yet another
  5079. * Observable in provided series, no matter if previous Observable completed or ended with an error. This will
  5080. * be happening until there is no more Observables left in the series, at which point returned Observable will
  5081. * complete - even if the last subscribed stream ended with an error.
  5082. *
  5083. * `onErrorResumeNext` can be therefore thought of as version of {@link concat} operator, which is more permissive
  5084. * when it comes to the errors emitted by its input Observables. While `concat` subscribes to the next Observable
  5085. * in series only if previous one successfully completed, `onErrorResumeNext` subscribes even if it ended with
  5086. * an error.
  5087. *
  5088. * Note that you do not get any access to errors emitted by the Observables. In particular do not
  5089. * expect these errors to appear in error callback passed to {@link subscribe}. If you want to take
  5090. * specific actions based on what error was emitted by an Observable, you should try out {@link catch} instead.
  5091. *
  5092. *
  5093. * @example <caption>Subscribe to the next Observable after map fails</caption>
  5094. * Rx.Observable.of(1, 2, 3, 0)
  5095. * .map(x => {
  5096. * if (x === 0) { throw Error(); }
  5097. return 10 / x;
  5098. * })
  5099. * .onErrorResumeNext(Rx.Observable.of(1, 2, 3))
  5100. * .subscribe(
  5101. * val => console.log(val),
  5102. * err => console.log(err), // Will never be called.
  5103. * () => console.log('that\'s it!')
  5104. * );
  5105. *
  5106. * // Logs:
  5107. * // 10
  5108. * // 5
  5109. * // 3.3333333333333335
  5110. * // 1
  5111. * // 2
  5112. * // 3
  5113. * // "that's it!"
  5114. *
  5115. * @see {@link concat}
  5116. * @see {@link catch}
  5117. *
  5118. * @param {...ObservableInput} observables Observables passed either directly or as an array.
  5119. * @return {Observable} An Observable that emits values from source Observable, but - if it errors - subscribes
  5120. * to the next passed Observable and so on, until it completes or runs out of Observables.
  5121. * @method onErrorResumeNext
  5122. * @owner Observable
  5123. */
  5124. function onErrorResumeNext$1() {
  5125. var nextSources = [];
  5126. for (var _i = 0; _i < arguments.length; _i++) {
  5127. nextSources[_i - 0] = arguments[_i];
  5128. }
  5129. if (nextSources.length === 1 && isArray(nextSources[0])) {
  5130. nextSources = nextSources[0];
  5131. }
  5132. return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); };
  5133. }
  5134. /* tslint:enable:max-line-length */
  5135. function onErrorResumeNextStatic() {
  5136. var nextSources = [];
  5137. for (var _i = 0; _i < arguments.length; _i++) {
  5138. nextSources[_i - 0] = arguments[_i];
  5139. }
  5140. var source = null;
  5141. if (nextSources.length === 1 && isArray(nextSources[0])) {
  5142. nextSources = nextSources[0];
  5143. }
  5144. source = nextSources.shift();
  5145. return new FromObservable(source, null).lift(new OnErrorResumeNextOperator(nextSources));
  5146. }
  5147. var OnErrorResumeNextOperator = (function () {
  5148. function OnErrorResumeNextOperator(nextSources) {
  5149. this.nextSources = nextSources;
  5150. }
  5151. OnErrorResumeNextOperator.prototype.call = function (subscriber, source) {
  5152. return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));
  5153. };
  5154. return OnErrorResumeNextOperator;
  5155. }());
  5156. var OnErrorResumeNextSubscriber = (function (_super) {
  5157. __extends(OnErrorResumeNextSubscriber, _super);
  5158. function OnErrorResumeNextSubscriber(destination, nextSources) {
  5159. _super.call(this, destination);
  5160. this.destination = destination;
  5161. this.nextSources = nextSources;
  5162. }
  5163. OnErrorResumeNextSubscriber.prototype.notifyError = function (error, innerSub) {
  5164. this.subscribeToNextSource();
  5165. };
  5166. OnErrorResumeNextSubscriber.prototype.notifyComplete = function (innerSub) {
  5167. this.subscribeToNextSource();
  5168. };
  5169. OnErrorResumeNextSubscriber.prototype._error = function (err) {
  5170. this.subscribeToNextSource();
  5171. };
  5172. OnErrorResumeNextSubscriber.prototype._complete = function () {
  5173. this.subscribeToNextSource();
  5174. };
  5175. OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () {
  5176. var next = this.nextSources.shift();
  5177. if (next) {
  5178. this.add(subscribeToResult(this, next));
  5179. }
  5180. else {
  5181. this.destination.complete();
  5182. }
  5183. };
  5184. return OnErrorResumeNextSubscriber;
  5185. }(OuterSubscriber));
  5186. var onErrorResumeNext$$1 = onErrorResumeNextStatic;
  5187. Observable.onErrorResumeNext = onErrorResumeNext$$1;
  5188. function dispatch$1(state) {
  5189. var obj = state.obj, keys = state.keys, length = state.length, index = state.index, subscriber = state.subscriber;
  5190. if (index === length) {
  5191. subscriber.complete();
  5192. return;
  5193. }
  5194. var key = keys[index];
  5195. subscriber.next([key, obj[key]]);
  5196. state.index = index + 1;
  5197. this.schedule(state);
  5198. }
  5199. /**
  5200. * We need this JSDoc comment for affecting ESDoc.
  5201. * @extends {Ignored}
  5202. * @hide true
  5203. */
  5204. var PairsObservable = (function (_super) {
  5205. __extends(PairsObservable, _super);
  5206. function PairsObservable(obj, scheduler) {
  5207. _super.call(this);
  5208. this.obj = obj;
  5209. this.scheduler = scheduler;
  5210. this.keys = Object.keys(obj);
  5211. }
  5212. /**
  5213. * Convert an object into an observable sequence of [key, value] pairs
  5214. * using an optional IScheduler to enumerate the object.
  5215. *
  5216. * @example <caption>Converts a javascript object to an Observable</caption>
  5217. * var obj = {
  5218. * foo: 42,
  5219. * bar: 56,
  5220. * baz: 78
  5221. * };
  5222. *
  5223. * var source = Rx.Observable.pairs(obj);
  5224. *
  5225. * var subscription = source.subscribe(
  5226. * function (x) {
  5227. * console.log('Next: %s', x);
  5228. * },
  5229. * function (err) {
  5230. * console.log('Error: %s', err);
  5231. * },
  5232. * function () {
  5233. * console.log('Completed');
  5234. * });
  5235. *
  5236. * @param {Object} obj The object to inspect and turn into an
  5237. * Observable sequence.
  5238. * @param {Scheduler} [scheduler] An optional IScheduler to run the
  5239. * enumeration of the input sequence on.
  5240. * @returns {(Observable<Array<string | T>>)} An observable sequence of
  5241. * [key, value] pairs from the object.
  5242. */
  5243. PairsObservable.create = function (obj, scheduler) {
  5244. return new PairsObservable(obj, scheduler);
  5245. };
  5246. /** @deprecated internal use only */ PairsObservable.prototype._subscribe = function (subscriber) {
  5247. var _a = this, keys = _a.keys, scheduler = _a.scheduler;
  5248. var length = keys.length;
  5249. if (scheduler) {
  5250. return scheduler.schedule(dispatch$1, 0, {
  5251. obj: this.obj, keys: keys, length: length, index: 0, subscriber: subscriber
  5252. });
  5253. }
  5254. else {
  5255. for (var idx = 0; idx < length; idx++) {
  5256. var key = keys[idx];
  5257. subscriber.next([key, this.obj[key]]);
  5258. }
  5259. subscriber.complete();
  5260. }
  5261. };
  5262. return PairsObservable;
  5263. }(Observable));
  5264. var pairs = PairsObservable.create;
  5265. Observable.pairs = pairs;
  5266. /**
  5267. * We need this JSDoc comment for affecting ESDoc.
  5268. * @extends {Ignored}
  5269. * @hide true
  5270. */
  5271. var RangeObservable = (function (_super) {
  5272. __extends(RangeObservable, _super);
  5273. function RangeObservable(start, count, scheduler) {
  5274. _super.call(this);
  5275. this.start = start;
  5276. this._count = count;
  5277. this.scheduler = scheduler;
  5278. }
  5279. /**
  5280. * Creates an Observable that emits a sequence of numbers within a specified
  5281. * range.
  5282. *
  5283. * <span class="informal">Emits a sequence of numbers in a range.</span>
  5284. *
  5285. * <img src="./img/range.png" width="100%">
  5286. *
  5287. * `range` operator emits a range of sequential integers, in order, where you
  5288. * select the `start` of the range and its `length`. By default, uses no
  5289. * IScheduler and just delivers the notifications synchronously, but may use
  5290. * an optional IScheduler to regulate those deliveries.
  5291. *
  5292. * @example <caption>Emits the numbers 1 to 10</caption>
  5293. * var numbers = Rx.Observable.range(1, 10);
  5294. * numbers.subscribe(x => console.log(x));
  5295. *
  5296. * @see {@link timer}
  5297. * @see {@link interval}
  5298. *
  5299. * @param {number} [start=0] The value of the first integer in the sequence.
  5300. * @param {number} [count=0] The number of sequential integers to generate.
  5301. * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
  5302. * the emissions of the notifications.
  5303. * @return {Observable} An Observable of numbers that emits a finite range of
  5304. * sequential integers.
  5305. * @static true
  5306. * @name range
  5307. * @owner Observable
  5308. */
  5309. RangeObservable.create = function (start, count, scheduler) {
  5310. if (start === void 0) { start = 0; }
  5311. if (count === void 0) { count = 0; }
  5312. return new RangeObservable(start, count, scheduler);
  5313. };
  5314. RangeObservable.dispatch = function (state) {
  5315. var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber;
  5316. if (index >= count) {
  5317. subscriber.complete();
  5318. return;
  5319. }
  5320. subscriber.next(start);
  5321. if (subscriber.closed) {
  5322. return;
  5323. }
  5324. state.index = index + 1;
  5325. state.start = start + 1;
  5326. this.schedule(state);
  5327. };
  5328. /** @deprecated internal use only */ RangeObservable.prototype._subscribe = function (subscriber) {
  5329. var index = 0;
  5330. var start = this.start;
  5331. var count = this._count;
  5332. var scheduler = this.scheduler;
  5333. if (scheduler) {
  5334. return scheduler.schedule(RangeObservable.dispatch, 0, {
  5335. index: index, count: count, start: start, subscriber: subscriber
  5336. });
  5337. }
  5338. else {
  5339. do {
  5340. if (index++ >= count) {
  5341. subscriber.complete();
  5342. break;
  5343. }
  5344. subscriber.next(start++);
  5345. if (subscriber.closed) {
  5346. break;
  5347. }
  5348. } while (true);
  5349. }
  5350. };
  5351. return RangeObservable;
  5352. }(Observable));
  5353. var range = RangeObservable.create;
  5354. Observable.range = range;
  5355. /**
  5356. * We need this JSDoc comment for affecting ESDoc.
  5357. * @extends {Ignored}
  5358. * @hide true
  5359. */
  5360. var UsingObservable = (function (_super) {
  5361. __extends(UsingObservable, _super);
  5362. function UsingObservable(resourceFactory, observableFactory) {
  5363. _super.call(this);
  5364. this.resourceFactory = resourceFactory;
  5365. this.observableFactory = observableFactory;
  5366. }
  5367. UsingObservable.create = function (resourceFactory, observableFactory) {
  5368. return new UsingObservable(resourceFactory, observableFactory);
  5369. };
  5370. /** @deprecated internal use only */ UsingObservable.prototype._subscribe = function (subscriber) {
  5371. var _a = this, resourceFactory = _a.resourceFactory, observableFactory = _a.observableFactory;
  5372. var resource;
  5373. try {
  5374. resource = resourceFactory();
  5375. return new UsingSubscriber(subscriber, resource, observableFactory);
  5376. }
  5377. catch (err) {
  5378. subscriber.error(err);
  5379. }
  5380. };
  5381. return UsingObservable;
  5382. }(Observable));
  5383. var UsingSubscriber = (function (_super) {
  5384. __extends(UsingSubscriber, _super);
  5385. function UsingSubscriber(destination, resource, observableFactory) {
  5386. _super.call(this, destination);
  5387. this.resource = resource;
  5388. this.observableFactory = observableFactory;
  5389. destination.add(resource);
  5390. this.tryUse();
  5391. }
  5392. UsingSubscriber.prototype.tryUse = function () {
  5393. try {
  5394. var source = this.observableFactory.call(this, this.resource);
  5395. if (source) {
  5396. this.add(subscribeToResult(this, source));
  5397. }
  5398. }
  5399. catch (err) {
  5400. this._error(err);
  5401. }
  5402. };
  5403. return UsingSubscriber;
  5404. }(OuterSubscriber));
  5405. var using = UsingObservable.create;
  5406. Observable.using = using;
  5407. /**
  5408. * We need this JSDoc comment for affecting ESDoc.
  5409. * @extends {Ignored}
  5410. * @hide true
  5411. */
  5412. var ErrorObservable = (function (_super) {
  5413. __extends(ErrorObservable, _super);
  5414. function ErrorObservable(error, scheduler) {
  5415. _super.call(this);
  5416. this.error = error;
  5417. this.scheduler = scheduler;
  5418. }
  5419. /**
  5420. * Creates an Observable that emits no items to the Observer and immediately
  5421. * emits an error notification.
  5422. *
  5423. * <span class="informal">Just emits 'error', and nothing else.
  5424. * </span>
  5425. *
  5426. * <img src="./img/throw.png" width="100%">
  5427. *
  5428. * This static operator is useful for creating a simple Observable that only
  5429. * emits the error notification. It can be used for composing with other
  5430. * Observables, such as in a {@link mergeMap}.
  5431. *
  5432. * @example <caption>Emit the number 7, then emit an error.</caption>
  5433. * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
  5434. * result.subscribe(x => console.log(x), e => console.error(e));
  5435. *
  5436. * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
  5437. * var interval = Rx.Observable.interval(1000);
  5438. * var result = interval.mergeMap(x =>
  5439. * x === 13 ?
  5440. * Rx.Observable.throw('Thirteens are bad') :
  5441. * Rx.Observable.of('a', 'b', 'c')
  5442. * );
  5443. * result.subscribe(x => console.log(x), e => console.error(e));
  5444. *
  5445. * @see {@link create}
  5446. * @see {@link empty}
  5447. * @see {@link never}
  5448. * @see {@link of}
  5449. *
  5450. * @param {any} error The particular Error to pass to the error notification.
  5451. * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
  5452. * the emission of the error notification.
  5453. * @return {Observable} An error Observable: emits only the error notification
  5454. * using the given error argument.
  5455. * @static true
  5456. * @name throw
  5457. * @owner Observable
  5458. */
  5459. ErrorObservable.create = function (error, scheduler) {
  5460. return new ErrorObservable(error, scheduler);
  5461. };
  5462. ErrorObservable.dispatch = function (arg) {
  5463. var error = arg.error, subscriber = arg.subscriber;
  5464. subscriber.error(error);
  5465. };
  5466. /** @deprecated internal use only */ ErrorObservable.prototype._subscribe = function (subscriber) {
  5467. var error = this.error;
  5468. var scheduler = this.scheduler;
  5469. subscriber.syncErrorThrowable = true;
  5470. if (scheduler) {
  5471. return scheduler.schedule(ErrorObservable.dispatch, 0, {
  5472. error: error, subscriber: subscriber
  5473. });
  5474. }
  5475. else {
  5476. subscriber.error(error);
  5477. }
  5478. };
  5479. return ErrorObservable;
  5480. }(Observable));
  5481. var _throw = ErrorObservable.create;
  5482. Observable.throw = _throw;
  5483. function isDate(value) {
  5484. return value instanceof Date && !isNaN(+value);
  5485. }
  5486. /**
  5487. * We need this JSDoc comment for affecting ESDoc.
  5488. * @extends {Ignored}
  5489. * @hide true
  5490. */
  5491. var TimerObservable = (function (_super) {
  5492. __extends(TimerObservable, _super);
  5493. function TimerObservable(dueTime, period, scheduler) {
  5494. if (dueTime === void 0) { dueTime = 0; }
  5495. _super.call(this);
  5496. this.period = -1;
  5497. this.dueTime = 0;
  5498. if (isNumeric(period)) {
  5499. this.period = Number(period) < 1 && 1 || Number(period);
  5500. }
  5501. else if (isScheduler(period)) {
  5502. scheduler = period;
  5503. }
  5504. if (!isScheduler(scheduler)) {
  5505. scheduler = async;
  5506. }
  5507. this.scheduler = scheduler;
  5508. this.dueTime = isDate(dueTime) ?
  5509. (+dueTime - this.scheduler.now()) :
  5510. dueTime;
  5511. }
  5512. /**
  5513. * Creates an Observable that starts emitting after an `initialDelay` and
  5514. * emits ever increasing numbers after each `period` of time thereafter.
  5515. *
  5516. * <span class="informal">Its like {@link interval}, but you can specify when
  5517. * should the emissions start.</span>
  5518. *
  5519. * <img src="./img/timer.png" width="100%">
  5520. *
  5521. * `timer` returns an Observable that emits an infinite sequence of ascending
  5522. * integers, with a constant interval of time, `period` of your choosing
  5523. * between those emissions. The first emission happens after the specified
  5524. * `initialDelay`. The initial delay may be a {@link Date}. By default, this
  5525. * operator uses the `async` IScheduler to provide a notion of time, but you
  5526. * may pass any IScheduler to it. If `period` is not specified, the output
  5527. * Observable emits only one value, `0`. Otherwise, it emits an infinite
  5528. * sequence.
  5529. *
  5530. * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
  5531. * var numbers = Rx.Observable.timer(3000, 1000);
  5532. * numbers.subscribe(x => console.log(x));
  5533. *
  5534. * @example <caption>Emits one number after five seconds</caption>
  5535. * var numbers = Rx.Observable.timer(5000);
  5536. * numbers.subscribe(x => console.log(x));
  5537. *
  5538. * @see {@link interval}
  5539. * @see {@link delay}
  5540. *
  5541. * @param {number|Date} initialDelay The initial delay time to wait before
  5542. * emitting the first value of `0`.
  5543. * @param {number} [period] The period of time between emissions of the
  5544. * subsequent numbers.
  5545. * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
  5546. * the emission of values, and providing a notion of "time".
  5547. * @return {Observable} An Observable that emits a `0` after the
  5548. * `initialDelay` and ever increasing numbers after each `period` of time
  5549. * thereafter.
  5550. * @static true
  5551. * @name timer
  5552. * @owner Observable
  5553. */
  5554. TimerObservable.create = function (initialDelay, period, scheduler) {
  5555. if (initialDelay === void 0) { initialDelay = 0; }
  5556. return new TimerObservable(initialDelay, period, scheduler);
  5557. };
  5558. TimerObservable.dispatch = function (state) {
  5559. var index = state.index, period = state.period, subscriber = state.subscriber;
  5560. var action = this;
  5561. subscriber.next(index);
  5562. if (subscriber.closed) {
  5563. return;
  5564. }
  5565. else if (period === -1) {
  5566. return subscriber.complete();
  5567. }
  5568. state.index = index + 1;
  5569. action.schedule(state, period);
  5570. };
  5571. /** @deprecated internal use only */ TimerObservable.prototype._subscribe = function (subscriber) {
  5572. var index = 0;
  5573. var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
  5574. return scheduler.schedule(TimerObservable.dispatch, dueTime, {
  5575. index: index, period: period, subscriber: subscriber
  5576. });
  5577. };
  5578. return TimerObservable;
  5579. }(Observable));
  5580. var timer = TimerObservable.create;
  5581. Observable.timer = timer;
  5582. /* tslint:enable:max-line-length */
  5583. /**
  5584. * @param observables
  5585. * @return {Observable<R>}
  5586. * @method zip
  5587. * @owner Observable
  5588. */
  5589. function zip$1() {
  5590. var observables = [];
  5591. for (var _i = 0; _i < arguments.length; _i++) {
  5592. observables[_i - 0] = arguments[_i];
  5593. }
  5594. return function zipOperatorFunction(source) {
  5595. return source.lift.call(zipStatic.apply(void 0, [source].concat(observables)));
  5596. };
  5597. }
  5598. /* tslint:enable:max-line-length */
  5599. /**
  5600. * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
  5601. * of its input Observables.
  5602. *
  5603. * If the latest parameter is a function, this function is used to compute the created value from the input values.
  5604. * Otherwise, an array of the input values is returned.
  5605. *
  5606. * @example <caption>Combine age and name from different sources</caption>
  5607. *
  5608. * let age$ = Observable.of<number>(27, 25, 29);
  5609. * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
  5610. * let isDev$ = Observable.of<boolean>(true, true, false);
  5611. *
  5612. * Observable
  5613. * .zip(age$,
  5614. * name$,
  5615. * isDev$,
  5616. * (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
  5617. * .subscribe(x => console.log(x));
  5618. *
  5619. * // outputs
  5620. * // { age: 27, name: 'Foo', isDev: true }
  5621. * // { age: 25, name: 'Bar', isDev: true }
  5622. * // { age: 29, name: 'Beer', isDev: false }
  5623. *
  5624. * @param observables
  5625. * @return {Observable<R>}
  5626. * @static true
  5627. * @name zip
  5628. * @owner Observable
  5629. */
  5630. function zipStatic() {
  5631. var observables = [];
  5632. for (var _i = 0; _i < arguments.length; _i++) {
  5633. observables[_i - 0] = arguments[_i];
  5634. }
  5635. var project = observables[observables.length - 1];
  5636. if (typeof project === 'function') {
  5637. observables.pop();
  5638. }
  5639. return new ArrayObservable(observables).lift(new ZipOperator(project));
  5640. }
  5641. var ZipOperator = (function () {
  5642. function ZipOperator(project) {
  5643. this.project = project;
  5644. }
  5645. ZipOperator.prototype.call = function (subscriber, source) {
  5646. return source.subscribe(new ZipSubscriber(subscriber, this.project));
  5647. };
  5648. return ZipOperator;
  5649. }());
  5650. /**
  5651. * We need this JSDoc comment for affecting ESDoc.
  5652. * @ignore
  5653. * @extends {Ignored}
  5654. */
  5655. var ZipSubscriber = (function (_super) {
  5656. __extends(ZipSubscriber, _super);
  5657. function ZipSubscriber(destination, project, values) {
  5658. if (values === void 0) { values = Object.create(null); }
  5659. _super.call(this, destination);
  5660. this.iterators = [];
  5661. this.active = 0;
  5662. this.project = (typeof project === 'function') ? project : null;
  5663. this.values = values;
  5664. }
  5665. ZipSubscriber.prototype._next = function (value) {
  5666. var iterators = this.iterators;
  5667. if (isArray(value)) {
  5668. iterators.push(new StaticArrayIterator(value));
  5669. }
  5670. else if (typeof value[iterator] === 'function') {
  5671. iterators.push(new StaticIterator(value[iterator]()));
  5672. }
  5673. else {
  5674. iterators.push(new ZipBufferIterator(this.destination, this, value));
  5675. }
  5676. };
  5677. ZipSubscriber.prototype._complete = function () {
  5678. var iterators = this.iterators;
  5679. var len = iterators.length;
  5680. if (len === 0) {
  5681. this.destination.complete();
  5682. return;
  5683. }
  5684. this.active = len;
  5685. for (var i = 0; i < len; i++) {
  5686. var iterator$$1 = iterators[i];
  5687. if (iterator$$1.stillUnsubscribed) {
  5688. this.add(iterator$$1.subscribe(iterator$$1, i));
  5689. }
  5690. else {
  5691. this.active--; // not an observable
  5692. }
  5693. }
  5694. };
  5695. ZipSubscriber.prototype.notifyInactive = function () {
  5696. this.active--;
  5697. if (this.active === 0) {
  5698. this.destination.complete();
  5699. }
  5700. };
  5701. ZipSubscriber.prototype.checkIterators = function () {
  5702. var iterators = this.iterators;
  5703. var len = iterators.length;
  5704. var destination = this.destination;
  5705. // abort if not all of them have values
  5706. for (var i = 0; i < len; i++) {
  5707. var iterator$$1 = iterators[i];
  5708. if (typeof iterator$$1.hasValue === 'function' && !iterator$$1.hasValue()) {
  5709. return;
  5710. }
  5711. }
  5712. var shouldComplete = false;
  5713. var args = [];
  5714. for (var i = 0; i < len; i++) {
  5715. var iterator$$1 = iterators[i];
  5716. var result = iterator$$1.next();
  5717. // check to see if it's completed now that you've gotten
  5718. // the next value.
  5719. if (iterator$$1.hasCompleted()) {
  5720. shouldComplete = true;
  5721. }
  5722. if (result.done) {
  5723. destination.complete();
  5724. return;
  5725. }
  5726. args.push(result.value);
  5727. }
  5728. if (this.project) {
  5729. this._tryProject(args);
  5730. }
  5731. else {
  5732. destination.next(args);
  5733. }
  5734. if (shouldComplete) {
  5735. destination.complete();
  5736. }
  5737. };
  5738. ZipSubscriber.prototype._tryProject = function (args) {
  5739. var result;
  5740. try {
  5741. result = this.project.apply(this, args);
  5742. }
  5743. catch (err) {
  5744. this.destination.error(err);
  5745. return;
  5746. }
  5747. this.destination.next(result);
  5748. };
  5749. return ZipSubscriber;
  5750. }(Subscriber));
  5751. var StaticIterator = (function () {
  5752. function StaticIterator(iterator$$1) {
  5753. this.iterator = iterator$$1;
  5754. this.nextResult = iterator$$1.next();
  5755. }
  5756. StaticIterator.prototype.hasValue = function () {
  5757. return true;
  5758. };
  5759. StaticIterator.prototype.next = function () {
  5760. var result = this.nextResult;
  5761. this.nextResult = this.iterator.next();
  5762. return result;
  5763. };
  5764. StaticIterator.prototype.hasCompleted = function () {
  5765. var nextResult = this.nextResult;
  5766. return nextResult && nextResult.done;
  5767. };
  5768. return StaticIterator;
  5769. }());
  5770. var StaticArrayIterator = (function () {
  5771. function StaticArrayIterator(array) {
  5772. this.array = array;
  5773. this.index = 0;
  5774. this.length = 0;
  5775. this.length = array.length;
  5776. }
  5777. StaticArrayIterator.prototype[iterator] = function () {
  5778. return this;
  5779. };
  5780. StaticArrayIterator.prototype.next = function (value) {
  5781. var i = this.index++;
  5782. var array = this.array;
  5783. return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
  5784. };
  5785. StaticArrayIterator.prototype.hasValue = function () {
  5786. return this.array.length > this.index;
  5787. };
  5788. StaticArrayIterator.prototype.hasCompleted = function () {
  5789. return this.array.length === this.index;
  5790. };
  5791. return StaticArrayIterator;
  5792. }());
  5793. /**
  5794. * We need this JSDoc comment for affecting ESDoc.
  5795. * @ignore
  5796. * @extends {Ignored}
  5797. */
  5798. var ZipBufferIterator = (function (_super) {
  5799. __extends(ZipBufferIterator, _super);
  5800. function ZipBufferIterator(destination, parent, observable) {
  5801. _super.call(this, destination);
  5802. this.parent = parent;
  5803. this.observable = observable;
  5804. this.stillUnsubscribed = true;
  5805. this.buffer = [];
  5806. this.isComplete = false;
  5807. }
  5808. ZipBufferIterator.prototype[iterator] = function () {
  5809. return this;
  5810. };
  5811. // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
  5812. // this is legit because `next()` will never be called by a subscription in this case.
  5813. ZipBufferIterator.prototype.next = function () {
  5814. var buffer = this.buffer;
  5815. if (buffer.length === 0 && this.isComplete) {
  5816. return { value: null, done: true };
  5817. }
  5818. else {
  5819. return { value: buffer.shift(), done: false };
  5820. }
  5821. };
  5822. ZipBufferIterator.prototype.hasValue = function () {
  5823. return this.buffer.length > 0;
  5824. };
  5825. ZipBufferIterator.prototype.hasCompleted = function () {
  5826. return this.buffer.length === 0 && this.isComplete;
  5827. };
  5828. ZipBufferIterator.prototype.notifyComplete = function () {
  5829. if (this.buffer.length > 0) {
  5830. this.isComplete = true;
  5831. this.parent.notifyInactive();
  5832. }
  5833. else {
  5834. this.destination.complete();
  5835. }
  5836. };
  5837. ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  5838. this.buffer.push(innerValue);
  5839. this.parent.checkIterators();
  5840. };
  5841. ZipBufferIterator.prototype.subscribe = function (value, index) {
  5842. return subscribeToResult(this, this.observable, this, index);
  5843. };
  5844. return ZipBufferIterator;
  5845. }(OuterSubscriber));
  5846. var zip$$1 = zipStatic;
  5847. Observable.zip = zip$$1;
  5848. /**
  5849. * Applies a given `project` function to each value emitted by the source
  5850. * Observable, and emits the resulting values as an Observable.
  5851. *
  5852. * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
  5853. * it passes each source value through a transformation function to get
  5854. * corresponding output values.</span>
  5855. *
  5856. * <img src="./img/map.png" width="100%">
  5857. *
  5858. * Similar to the well known `Array.prototype.map` function, this operator
  5859. * applies a projection to each value and emits that projection in the output
  5860. * Observable.
  5861. *
  5862. * @example <caption>Map every click to the clientX position of that click</caption>
  5863. * var clicks = Rx.Observable.fromEvent(document, 'click');
  5864. * var positions = clicks.map(ev => ev.clientX);
  5865. * positions.subscribe(x => console.log(x));
  5866. *
  5867. * @see {@link mapTo}
  5868. * @see {@link pluck}
  5869. *
  5870. * @param {function(value: T, index: number): R} project The function to apply
  5871. * to each `value` emitted by the source Observable. The `index` parameter is
  5872. * the number `i` for the i-th emission that has happened since the
  5873. * subscription, starting from the number `0`.
  5874. * @param {any} [thisArg] An optional argument to define what `this` is in the
  5875. * `project` function.
  5876. * @return {Observable<R>} An Observable that emits the values from the source
  5877. * Observable transformed by the given `project` function.
  5878. * @method map
  5879. * @owner Observable
  5880. */
  5881. function map(project, thisArg) {
  5882. return function mapOperation(source) {
  5883. if (typeof project !== 'function') {
  5884. throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
  5885. }
  5886. return source.lift(new MapOperator(project, thisArg));
  5887. };
  5888. }
  5889. var MapOperator = (function () {
  5890. function MapOperator(project, thisArg) {
  5891. this.project = project;
  5892. this.thisArg = thisArg;
  5893. }
  5894. MapOperator.prototype.call = function (subscriber, source) {
  5895. return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
  5896. };
  5897. return MapOperator;
  5898. }());
  5899. /**
  5900. * We need this JSDoc comment for affecting ESDoc.
  5901. * @ignore
  5902. * @extends {Ignored}
  5903. */
  5904. var MapSubscriber = (function (_super) {
  5905. __extends(MapSubscriber, _super);
  5906. function MapSubscriber(destination, project, thisArg) {
  5907. _super.call(this, destination);
  5908. this.project = project;
  5909. this.count = 0;
  5910. this.thisArg = thisArg || this;
  5911. }
  5912. // NOTE: This looks unoptimized, but it's actually purposefully NOT
  5913. // using try/catch optimizations.
  5914. MapSubscriber.prototype._next = function (value) {
  5915. var result;
  5916. try {
  5917. result = this.project.call(this.thisArg, value, this.count++);
  5918. }
  5919. catch (err) {
  5920. this.destination.error(err);
  5921. return;
  5922. }
  5923. this.destination.next(result);
  5924. };
  5925. return MapSubscriber;
  5926. }(Subscriber));
  5927. function getCORSRequest() {
  5928. if (_root.XMLHttpRequest) {
  5929. return new _root.XMLHttpRequest();
  5930. }
  5931. else if (!!_root.XDomainRequest) {
  5932. return new _root.XDomainRequest();
  5933. }
  5934. else {
  5935. throw new Error('CORS is not supported by your browser');
  5936. }
  5937. }
  5938. function getXMLHttpRequest() {
  5939. if (_root.XMLHttpRequest) {
  5940. return new _root.XMLHttpRequest();
  5941. }
  5942. else {
  5943. var progId = void 0;
  5944. try {
  5945. var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
  5946. for (var i = 0; i < 3; i++) {
  5947. try {
  5948. progId = progIds[i];
  5949. if (new _root.ActiveXObject(progId)) {
  5950. break;
  5951. }
  5952. }
  5953. catch (e) {
  5954. }
  5955. }
  5956. return new _root.ActiveXObject(progId);
  5957. }
  5958. catch (e) {
  5959. throw new Error('XMLHttpRequest is not supported by your browser');
  5960. }
  5961. }
  5962. }
  5963. function ajaxGet(url, headers) {
  5964. if (headers === void 0) { headers = null; }
  5965. return new AjaxObservable({ method: 'GET', url: url, headers: headers });
  5966. }
  5967. function ajaxPost(url, body, headers) {
  5968. return new AjaxObservable({ method: 'POST', url: url, body: body, headers: headers });
  5969. }
  5970. function ajaxDelete(url, headers) {
  5971. return new AjaxObservable({ method: 'DELETE', url: url, headers: headers });
  5972. }
  5973. function ajaxPut(url, body, headers) {
  5974. return new AjaxObservable({ method: 'PUT', url: url, body: body, headers: headers });
  5975. }
  5976. function ajaxPatch(url, body, headers) {
  5977. return new AjaxObservable({ method: 'PATCH', url: url, body: body, headers: headers });
  5978. }
  5979. var mapResponse = map(function (x, index) { return x.response; });
  5980. function ajaxGetJSON(url, headers) {
  5981. return mapResponse(new AjaxObservable({
  5982. method: 'GET',
  5983. url: url,
  5984. responseType: 'json',
  5985. headers: headers
  5986. }));
  5987. }
  5988. /**
  5989. * We need this JSDoc comment for affecting ESDoc.
  5990. * @extends {Ignored}
  5991. * @hide true
  5992. */
  5993. var AjaxObservable = (function (_super) {
  5994. __extends(AjaxObservable, _super);
  5995. function AjaxObservable(urlOrRequest) {
  5996. _super.call(this);
  5997. var request = {
  5998. async: true,
  5999. createXHR: function () {
  6000. return this.crossDomain ? getCORSRequest.call(this) : getXMLHttpRequest();
  6001. },
  6002. crossDomain: false,
  6003. withCredentials: false,
  6004. headers: {},
  6005. method: 'GET',
  6006. responseType: 'json',
  6007. timeout: 0
  6008. };
  6009. if (typeof urlOrRequest === 'string') {
  6010. request.url = urlOrRequest;
  6011. }
  6012. else {
  6013. for (var prop in urlOrRequest) {
  6014. if (urlOrRequest.hasOwnProperty(prop)) {
  6015. request[prop] = urlOrRequest[prop];
  6016. }
  6017. }
  6018. }
  6019. this.request = request;
  6020. }
  6021. /** @deprecated internal use only */ AjaxObservable.prototype._subscribe = function (subscriber) {
  6022. return new AjaxSubscriber(subscriber, this.request);
  6023. };
  6024. /**
  6025. * Creates an observable for an Ajax request with either a request object with
  6026. * url, headers, etc or a string for a URL.
  6027. *
  6028. * @example
  6029. * source = Rx.Observable.ajax('/products');
  6030. * source = Rx.Observable.ajax({ url: 'products', method: 'GET' });
  6031. *
  6032. * @param {string|Object} request Can be one of the following:
  6033. * A string of the URL to make the Ajax call.
  6034. * An object with the following properties
  6035. * - url: URL of the request
  6036. * - body: The body of the request
  6037. * - method: Method of the request, such as GET, POST, PUT, PATCH, DELETE
  6038. * - async: Whether the request is async
  6039. * - headers: Optional headers
  6040. * - crossDomain: true if a cross domain request, else false
  6041. * - createXHR: a function to override if you need to use an alternate
  6042. * XMLHttpRequest implementation.
  6043. * - resultSelector: a function to use to alter the output value type of
  6044. * the Observable. Gets {@link AjaxResponse} as an argument.
  6045. * @return {Observable} An observable sequence containing the XMLHttpRequest.
  6046. * @static true
  6047. * @name ajax
  6048. * @owner Observable
  6049. */
  6050. AjaxObservable.create = (function () {
  6051. var create = function (urlOrRequest) {
  6052. return new AjaxObservable(urlOrRequest);
  6053. };
  6054. create.get = ajaxGet;
  6055. create.post = ajaxPost;
  6056. create.delete = ajaxDelete;
  6057. create.put = ajaxPut;
  6058. create.patch = ajaxPatch;
  6059. create.getJSON = ajaxGetJSON;
  6060. return create;
  6061. })();
  6062. return AjaxObservable;
  6063. }(Observable));
  6064. /**
  6065. * We need this JSDoc comment for affecting ESDoc.
  6066. * @ignore
  6067. * @extends {Ignored}
  6068. */
  6069. var AjaxSubscriber = (function (_super) {
  6070. __extends(AjaxSubscriber, _super);
  6071. function AjaxSubscriber(destination, request) {
  6072. _super.call(this, destination);
  6073. this.request = request;
  6074. this.done = false;
  6075. var headers = request.headers = request.headers || {};
  6076. // force CORS if requested
  6077. if (!request.crossDomain && !headers['X-Requested-With']) {
  6078. headers['X-Requested-With'] = 'XMLHttpRequest';
  6079. }
  6080. // ensure content type is set
  6081. if (!('Content-Type' in headers) && !(_root.FormData && request.body instanceof _root.FormData) && typeof request.body !== 'undefined') {
  6082. headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  6083. }
  6084. // properly serialize body
  6085. request.body = this.serializeBody(request.body, request.headers['Content-Type']);
  6086. this.send();
  6087. }
  6088. AjaxSubscriber.prototype.next = function (e) {
  6089. this.done = true;
  6090. var _a = this, xhr = _a.xhr, request = _a.request, destination = _a.destination;
  6091. var response = new AjaxResponse(e, xhr, request);
  6092. destination.next(response);
  6093. };
  6094. AjaxSubscriber.prototype.send = function () {
  6095. var _a = this, request = _a.request, _b = _a.request, user = _b.user, method = _b.method, url = _b.url, async = _b.async, password = _b.password, headers = _b.headers, body = _b.body;
  6096. var createXHR = request.createXHR;
  6097. var xhr = tryCatch(createXHR).call(request);
  6098. if (xhr === errorObject) {
  6099. this.error(errorObject.e);
  6100. }
  6101. else {
  6102. this.xhr = xhr;
  6103. // set up the events before open XHR
  6104. // https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
  6105. // You need to add the event listeners before calling open() on the request.
  6106. // Otherwise the progress events will not fire.
  6107. this.setupEvents(xhr, request);
  6108. // open XHR
  6109. var result = void 0;
  6110. if (user) {
  6111. result = tryCatch(xhr.open).call(xhr, method, url, async, user, password);
  6112. }
  6113. else {
  6114. result = tryCatch(xhr.open).call(xhr, method, url, async);
  6115. }
  6116. if (result === errorObject) {
  6117. this.error(errorObject.e);
  6118. return null;
  6119. }
  6120. // timeout, responseType and withCredentials can be set once the XHR is open
  6121. if (async) {
  6122. xhr.timeout = request.timeout;
  6123. xhr.responseType = request.responseType;
  6124. }
  6125. if ('withCredentials' in xhr) {
  6126. xhr.withCredentials = !!request.withCredentials;
  6127. }
  6128. // set headers
  6129. this.setHeaders(xhr, headers);
  6130. // finally send the request
  6131. result = body ? tryCatch(xhr.send).call(xhr, body) : tryCatch(xhr.send).call(xhr);
  6132. if (result === errorObject) {
  6133. this.error(errorObject.e);
  6134. return null;
  6135. }
  6136. }
  6137. return xhr;
  6138. };
  6139. AjaxSubscriber.prototype.serializeBody = function (body, contentType) {
  6140. if (!body || typeof body === 'string') {
  6141. return body;
  6142. }
  6143. else if (_root.FormData && body instanceof _root.FormData) {
  6144. return body;
  6145. }
  6146. if (contentType) {
  6147. var splitIndex = contentType.indexOf(';');
  6148. if (splitIndex !== -1) {
  6149. contentType = contentType.substring(0, splitIndex);
  6150. }
  6151. }
  6152. switch (contentType) {
  6153. case 'application/x-www-form-urlencoded':
  6154. return Object.keys(body).map(function (key) { return (encodeURIComponent(key) + "=" + encodeURIComponent(body[key])); }).join('&');
  6155. case 'application/json':
  6156. return JSON.stringify(body);
  6157. default:
  6158. return body;
  6159. }
  6160. };
  6161. AjaxSubscriber.prototype.setHeaders = function (xhr, headers) {
  6162. for (var key in headers) {
  6163. if (headers.hasOwnProperty(key)) {
  6164. xhr.setRequestHeader(key, headers[key]);
  6165. }
  6166. }
  6167. };
  6168. AjaxSubscriber.prototype.setupEvents = function (xhr, request) {
  6169. var progressSubscriber = request.progressSubscriber;
  6170. function xhrTimeout(e) {
  6171. var _a = xhrTimeout, subscriber = _a.subscriber, progressSubscriber = _a.progressSubscriber, request = _a.request;
  6172. if (progressSubscriber) {
  6173. progressSubscriber.error(e);
  6174. }
  6175. subscriber.error(new AjaxTimeoutError(this, request)); //TODO: Make betterer.
  6176. }
  6177. xhr.ontimeout = xhrTimeout;
  6178. xhrTimeout.request = request;
  6179. xhrTimeout.subscriber = this;
  6180. xhrTimeout.progressSubscriber = progressSubscriber;
  6181. if (xhr.upload && 'withCredentials' in xhr) {
  6182. if (progressSubscriber) {
  6183. var xhrProgress_1;
  6184. xhrProgress_1 = function (e) {
  6185. var progressSubscriber = xhrProgress_1.progressSubscriber;
  6186. progressSubscriber.next(e);
  6187. };
  6188. if (_root.XDomainRequest) {
  6189. xhr.onprogress = xhrProgress_1;
  6190. }
  6191. else {
  6192. xhr.upload.onprogress = xhrProgress_1;
  6193. }
  6194. xhrProgress_1.progressSubscriber = progressSubscriber;
  6195. }
  6196. var xhrError_1;
  6197. xhrError_1 = function (e) {
  6198. var _a = xhrError_1, progressSubscriber = _a.progressSubscriber, subscriber = _a.subscriber, request = _a.request;
  6199. if (progressSubscriber) {
  6200. progressSubscriber.error(e);
  6201. }
  6202. subscriber.error(new AjaxError('ajax error', this, request));
  6203. };
  6204. xhr.onerror = xhrError_1;
  6205. xhrError_1.request = request;
  6206. xhrError_1.subscriber = this;
  6207. xhrError_1.progressSubscriber = progressSubscriber;
  6208. }
  6209. function xhrReadyStateChange(e) {
  6210. var _a = xhrReadyStateChange, subscriber = _a.subscriber, progressSubscriber = _a.progressSubscriber, request = _a.request;
  6211. if (this.readyState === 4) {
  6212. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  6213. var status_1 = this.status === 1223 ? 204 : this.status;
  6214. var response = (this.responseType === 'text' ? (this.response || this.responseText) : this.response);
  6215. // fix status code when it is 0 (0 status is undocumented).
  6216. // Occurs when accessing file resources or on Android 4.1 stock browser
  6217. // while retrieving files from application cache.
  6218. if (status_1 === 0) {
  6219. status_1 = response ? 200 : 0;
  6220. }
  6221. if (200 <= status_1 && status_1 < 300) {
  6222. if (progressSubscriber) {
  6223. progressSubscriber.complete();
  6224. }
  6225. subscriber.next(e);
  6226. subscriber.complete();
  6227. }
  6228. else {
  6229. if (progressSubscriber) {
  6230. progressSubscriber.error(e);
  6231. }
  6232. subscriber.error(new AjaxError('ajax error ' + status_1, this, request));
  6233. }
  6234. }
  6235. }
  6236. xhr.onreadystatechange = xhrReadyStateChange;
  6237. xhrReadyStateChange.subscriber = this;
  6238. xhrReadyStateChange.progressSubscriber = progressSubscriber;
  6239. xhrReadyStateChange.request = request;
  6240. };
  6241. AjaxSubscriber.prototype.unsubscribe = function () {
  6242. var _a = this, done = _a.done, xhr = _a.xhr;
  6243. if (!done && xhr && xhr.readyState !== 4 && typeof xhr.abort === 'function') {
  6244. xhr.abort();
  6245. }
  6246. _super.prototype.unsubscribe.call(this);
  6247. };
  6248. return AjaxSubscriber;
  6249. }(Subscriber));
  6250. /**
  6251. * A normalized AJAX response.
  6252. *
  6253. * @see {@link ajax}
  6254. *
  6255. * @class AjaxResponse
  6256. */
  6257. var AjaxResponse = (function () {
  6258. function AjaxResponse(originalEvent, xhr, request) {
  6259. this.originalEvent = originalEvent;
  6260. this.xhr = xhr;
  6261. this.request = request;
  6262. this.status = xhr.status;
  6263. this.responseType = xhr.responseType || request.responseType;
  6264. this.response = parseXhrResponse(this.responseType, xhr);
  6265. }
  6266. return AjaxResponse;
  6267. }());
  6268. /**
  6269. * A normalized AJAX error.
  6270. *
  6271. * @see {@link ajax}
  6272. *
  6273. * @class AjaxError
  6274. */
  6275. var AjaxError = (function (_super) {
  6276. __extends(AjaxError, _super);
  6277. function AjaxError(message, xhr, request) {
  6278. _super.call(this, message);
  6279. this.message = message;
  6280. this.xhr = xhr;
  6281. this.request = request;
  6282. this.status = xhr.status;
  6283. this.responseType = xhr.responseType || request.responseType;
  6284. this.response = parseXhrResponse(this.responseType, xhr);
  6285. }
  6286. return AjaxError;
  6287. }(Error));
  6288. function parseXhrResponse(responseType, xhr) {
  6289. switch (responseType) {
  6290. case 'json':
  6291. if ('response' in xhr) {
  6292. //IE does not support json as responseType, parse it internally
  6293. return xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || 'null');
  6294. }
  6295. else {
  6296. // HACK(benlesh): TypeScript shennanigans
  6297. // tslint:disable-next-line:no-any latest TS seems to think xhr is "never" here.
  6298. return JSON.parse(xhr.responseText || 'null');
  6299. }
  6300. case 'xml':
  6301. return xhr.responseXML;
  6302. case 'text':
  6303. default:
  6304. // HACK(benlesh): TypeScript shennanigans
  6305. // tslint:disable-next-line:no-any latest TS seems to think xhr is "never" here.
  6306. return ('response' in xhr) ? xhr.response : xhr.responseText;
  6307. }
  6308. }
  6309. /**
  6310. * @see {@link ajax}
  6311. *
  6312. * @class AjaxTimeoutError
  6313. */
  6314. var AjaxTimeoutError = (function (_super) {
  6315. __extends(AjaxTimeoutError, _super);
  6316. function AjaxTimeoutError(xhr, request) {
  6317. _super.call(this, 'ajax timeout', xhr, request);
  6318. }
  6319. return AjaxTimeoutError;
  6320. }(AjaxError));
  6321. var ajax = AjaxObservable.create;
  6322. Observable.ajax = ajax;
  6323. /**
  6324. * We need this JSDoc comment for affecting ESDoc.
  6325. * @ignore
  6326. * @extends {Ignored}
  6327. */
  6328. var QueueAction = (function (_super) {
  6329. __extends(QueueAction, _super);
  6330. function QueueAction(scheduler, work) {
  6331. _super.call(this, scheduler, work);
  6332. this.scheduler = scheduler;
  6333. this.work = work;
  6334. }
  6335. QueueAction.prototype.schedule = function (state, delay) {
  6336. if (delay === void 0) { delay = 0; }
  6337. if (delay > 0) {
  6338. return _super.prototype.schedule.call(this, state, delay);
  6339. }
  6340. this.delay = delay;
  6341. this.state = state;
  6342. this.scheduler.flush(this);
  6343. return this;
  6344. };
  6345. QueueAction.prototype.execute = function (state, delay) {
  6346. return (delay > 0 || this.closed) ?
  6347. _super.prototype.execute.call(this, state, delay) :
  6348. this._execute(state, delay);
  6349. };
  6350. QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
  6351. if (delay === void 0) { delay = 0; }
  6352. // If delay exists and is greater than 0, or if the delay is null (the
  6353. // action wasn't rescheduled) but was originally scheduled as an async
  6354. // action, then recycle as an async action.
  6355. if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
  6356. return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
  6357. }
  6358. // Otherwise flush the scheduler starting with this action.
  6359. return scheduler.flush(this);
  6360. };
  6361. return QueueAction;
  6362. }(AsyncAction));
  6363. var QueueScheduler = (function (_super) {
  6364. __extends(QueueScheduler, _super);
  6365. function QueueScheduler() {
  6366. _super.apply(this, arguments);
  6367. }
  6368. return QueueScheduler;
  6369. }(AsyncScheduler));
  6370. /**
  6371. *
  6372. * Queue Scheduler
  6373. *
  6374. * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
  6375. *
  6376. * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
  6377. *
  6378. * When used without delay, it schedules given task synchronously - executes it right when
  6379. * it is scheduled. However when called recursively, that is when inside the scheduled task,
  6380. * another task is scheduled with queue scheduler, instead of executing immediately as well,
  6381. * that task will be put on a queue and wait for current one to finish.
  6382. *
  6383. * This means that when you execute task with `queue` scheduler, you are sure it will end
  6384. * before any other task scheduled with that scheduler will start.
  6385. *
  6386. * @examples <caption>Schedule recursively first, then do something</caption>
  6387. *
  6388. * Rx.Scheduler.queue.schedule(() => {
  6389. * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
  6390. *
  6391. * console.log('first');
  6392. * });
  6393. *
  6394. * // Logs:
  6395. * // "first"
  6396. * // "second"
  6397. *
  6398. *
  6399. * @example <caption>Reschedule itself recursively</caption>
  6400. *
  6401. * Rx.Scheduler.queue.schedule(function(state) {
  6402. * if (state !== 0) {
  6403. * console.log('before', state);
  6404. * this.schedule(state - 1); // `this` references currently executing Action,
  6405. * // which we reschedule with new state
  6406. * console.log('after', state);
  6407. * }
  6408. * }, 0, 3);
  6409. *
  6410. * // In scheduler that runs recursively, you would expect:
  6411. * // "before", 3
  6412. * // "before", 2
  6413. * // "before", 1
  6414. * // "after", 1
  6415. * // "after", 2
  6416. * // "after", 3
  6417. *
  6418. * // But with queue it logs:
  6419. * // "before", 3
  6420. * // "after", 3
  6421. * // "before", 2
  6422. * // "after", 2
  6423. * // "before", 1
  6424. * // "after", 1
  6425. *
  6426. *
  6427. * @static true
  6428. * @name queue
  6429. * @owner Scheduler
  6430. */
  6431. var queue = new QueueScheduler(QueueAction);
  6432. /**
  6433. * @class ReplaySubject<T>
  6434. */
  6435. var ReplaySubject = (function (_super) {
  6436. __extends(ReplaySubject, _super);
  6437. function ReplaySubject(bufferSize, windowTime, scheduler) {
  6438. if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
  6439. if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
  6440. _super.call(this);
  6441. this.scheduler = scheduler;
  6442. this._events = [];
  6443. this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
  6444. this._windowTime = windowTime < 1 ? 1 : windowTime;
  6445. }
  6446. ReplaySubject.prototype.next = function (value) {
  6447. var now = this._getNow();
  6448. this._events.push(new ReplayEvent(now, value));
  6449. this._trimBufferThenGetEvents();
  6450. _super.prototype.next.call(this, value);
  6451. };
  6452. /** @deprecated internal use only */ ReplaySubject.prototype._subscribe = function (subscriber) {
  6453. var _events = this._trimBufferThenGetEvents();
  6454. var scheduler = this.scheduler;
  6455. var subscription;
  6456. if (this.closed) {
  6457. throw new ObjectUnsubscribedError();
  6458. }
  6459. else if (this.hasError) {
  6460. subscription = Subscription.EMPTY;
  6461. }
  6462. else if (this.isStopped) {
  6463. subscription = Subscription.EMPTY;
  6464. }
  6465. else {
  6466. this.observers.push(subscriber);
  6467. subscription = new SubjectSubscription(this, subscriber);
  6468. }
  6469. if (scheduler) {
  6470. subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));
  6471. }
  6472. var len = _events.length;
  6473. for (var i = 0; i < len && !subscriber.closed; i++) {
  6474. subscriber.next(_events[i].value);
  6475. }
  6476. if (this.hasError) {
  6477. subscriber.error(this.thrownError);
  6478. }
  6479. else if (this.isStopped) {
  6480. subscriber.complete();
  6481. }
  6482. return subscription;
  6483. };
  6484. ReplaySubject.prototype._getNow = function () {
  6485. return (this.scheduler || queue).now();
  6486. };
  6487. ReplaySubject.prototype._trimBufferThenGetEvents = function () {
  6488. var now = this._getNow();
  6489. var _bufferSize = this._bufferSize;
  6490. var _windowTime = this._windowTime;
  6491. var _events = this._events;
  6492. var eventsCount = _events.length;
  6493. var spliceCount = 0;
  6494. // Trim events that fall out of the time window.
  6495. // Start at the front of the list. Break early once
  6496. // we encounter an event that falls within the window.
  6497. while (spliceCount < eventsCount) {
  6498. if ((now - _events[spliceCount].time) < _windowTime) {
  6499. break;
  6500. }
  6501. spliceCount++;
  6502. }
  6503. if (eventsCount > _bufferSize) {
  6504. spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
  6505. }
  6506. if (spliceCount > 0) {
  6507. _events.splice(0, spliceCount);
  6508. }
  6509. return _events;
  6510. };
  6511. return ReplaySubject;
  6512. }(Subject));
  6513. var ReplayEvent = (function () {
  6514. function ReplayEvent(time, value) {
  6515. this.time = time;
  6516. this.value = value;
  6517. }
  6518. return ReplayEvent;
  6519. }());
  6520. function assignImpl(target) {
  6521. var sources = [];
  6522. for (var _i = 1; _i < arguments.length; _i++) {
  6523. sources[_i - 1] = arguments[_i];
  6524. }
  6525. var len = sources.length;
  6526. for (var i = 0; i < len; i++) {
  6527. var source = sources[i];
  6528. for (var k in source) {
  6529. if (source.hasOwnProperty(k)) {
  6530. target[k] = source[k];
  6531. }
  6532. }
  6533. }
  6534. return target;
  6535. }
  6536. function getAssign(root$$1) {
  6537. return root$$1.Object.assign || assignImpl;
  6538. }
  6539. var assign = getAssign(_root);
  6540. /**
  6541. * We need this JSDoc comment for affecting ESDoc.
  6542. * @extends {Ignored}
  6543. * @hide true
  6544. */
  6545. var WebSocketSubject = (function (_super) {
  6546. __extends(WebSocketSubject, _super);
  6547. function WebSocketSubject(urlConfigOrSource, destination) {
  6548. if (urlConfigOrSource instanceof Observable) {
  6549. _super.call(this, destination, urlConfigOrSource);
  6550. }
  6551. else {
  6552. _super.call(this);
  6553. this.WebSocketCtor = _root.WebSocket;
  6554. this._output = new Subject();
  6555. if (typeof urlConfigOrSource === 'string') {
  6556. this.url = urlConfigOrSource;
  6557. }
  6558. else {
  6559. // WARNING: config object could override important members here.
  6560. assign(this, urlConfigOrSource);
  6561. }
  6562. if (!this.WebSocketCtor) {
  6563. throw new Error('no WebSocket constructor can be found');
  6564. }
  6565. this.destination = new ReplaySubject();
  6566. }
  6567. }
  6568. WebSocketSubject.prototype.resultSelector = function (e) {
  6569. return JSON.parse(e.data);
  6570. };
  6571. /**
  6572. * Wrapper around the w3c-compatible WebSocket object provided by the browser.
  6573. *
  6574. * @example <caption>Wraps browser WebSocket</caption>
  6575. *
  6576. * let socket$ = Observable.webSocket('ws://localhost:8081');
  6577. *
  6578. * socket$.subscribe(
  6579. * (msg) => console.log('message received: ' + msg),
  6580. * (err) => console.log(err),
  6581. * () => console.log('complete')
  6582. * );
  6583. *
  6584. * socket$.next(JSON.stringify({ op: 'hello' }));
  6585. *
  6586. * @example <caption>Wraps WebSocket from nodejs-websocket (using node.js)</caption>
  6587. *
  6588. * import { w3cwebsocket } from 'websocket';
  6589. *
  6590. * let socket$ = Observable.webSocket({
  6591. * url: 'ws://localhost:8081',
  6592. * WebSocketCtor: w3cwebsocket
  6593. * });
  6594. *
  6595. * socket$.subscribe(
  6596. * (msg) => console.log('message received: ' + msg),
  6597. * (err) => console.log(err),
  6598. * () => console.log('complete')
  6599. * );
  6600. *
  6601. * socket$.next(JSON.stringify({ op: 'hello' }));
  6602. *
  6603. * @param {string | WebSocketSubjectConfig} urlConfigOrSource the source of the websocket as an url or a structure defining the websocket object
  6604. * @return {WebSocketSubject}
  6605. * @static true
  6606. * @name webSocket
  6607. * @owner Observable
  6608. */
  6609. WebSocketSubject.create = function (urlConfigOrSource) {
  6610. return new WebSocketSubject(urlConfigOrSource);
  6611. };
  6612. WebSocketSubject.prototype.lift = function (operator) {
  6613. var sock = new WebSocketSubject(this, this.destination);
  6614. sock.operator = operator;
  6615. return sock;
  6616. };
  6617. WebSocketSubject.prototype._resetState = function () {
  6618. this.socket = null;
  6619. if (!this.source) {
  6620. this.destination = new ReplaySubject();
  6621. }
  6622. this._output = new Subject();
  6623. };
  6624. // TODO: factor this out to be a proper Operator/Subscriber implementation and eliminate closures
  6625. WebSocketSubject.prototype.multiplex = function (subMsg, unsubMsg, messageFilter) {
  6626. var self = this;
  6627. return new Observable(function (observer) {
  6628. var result = tryCatch(subMsg)();
  6629. if (result === errorObject) {
  6630. observer.error(errorObject.e);
  6631. }
  6632. else {
  6633. self.next(result);
  6634. }
  6635. var subscription = self.subscribe(function (x) {
  6636. var result = tryCatch(messageFilter)(x);
  6637. if (result === errorObject) {
  6638. observer.error(errorObject.e);
  6639. }
  6640. else if (result) {
  6641. observer.next(x);
  6642. }
  6643. }, function (err) { return observer.error(err); }, function () { return observer.complete(); });
  6644. return function () {
  6645. var result = tryCatch(unsubMsg)();
  6646. if (result === errorObject) {
  6647. observer.error(errorObject.e);
  6648. }
  6649. else {
  6650. self.next(result);
  6651. }
  6652. subscription.unsubscribe();
  6653. };
  6654. });
  6655. };
  6656. WebSocketSubject.prototype._connectSocket = function () {
  6657. var _this = this;
  6658. var WebSocketCtor = this.WebSocketCtor;
  6659. var observer = this._output;
  6660. var socket = null;
  6661. try {
  6662. socket = this.protocol ?
  6663. new WebSocketCtor(this.url, this.protocol) :
  6664. new WebSocketCtor(this.url);
  6665. this.socket = socket;
  6666. if (this.binaryType) {
  6667. this.socket.binaryType = this.binaryType;
  6668. }
  6669. }
  6670. catch (e) {
  6671. observer.error(e);
  6672. return;
  6673. }
  6674. var subscription = new Subscription(function () {
  6675. _this.socket = null;
  6676. if (socket && socket.readyState === 1) {
  6677. socket.close();
  6678. }
  6679. });
  6680. socket.onopen = function (e) {
  6681. var openObserver = _this.openObserver;
  6682. if (openObserver) {
  6683. openObserver.next(e);
  6684. }
  6685. var queue = _this.destination;
  6686. _this.destination = Subscriber.create(function (x) { return socket.readyState === 1 && socket.send(x); }, function (e) {
  6687. var closingObserver = _this.closingObserver;
  6688. if (closingObserver) {
  6689. closingObserver.next(undefined);
  6690. }
  6691. if (e && e.code) {
  6692. socket.close(e.code, e.reason);
  6693. }
  6694. else {
  6695. observer.error(new TypeError('WebSocketSubject.error must be called with an object with an error code, ' +
  6696. 'and an optional reason: { code: number, reason: string }'));
  6697. }
  6698. _this._resetState();
  6699. }, function () {
  6700. var closingObserver = _this.closingObserver;
  6701. if (closingObserver) {
  6702. closingObserver.next(undefined);
  6703. }
  6704. socket.close();
  6705. _this._resetState();
  6706. });
  6707. if (queue && queue instanceof ReplaySubject) {
  6708. subscription.add(queue.subscribe(_this.destination));
  6709. }
  6710. };
  6711. socket.onerror = function (e) {
  6712. _this._resetState();
  6713. observer.error(e);
  6714. };
  6715. socket.onclose = function (e) {
  6716. _this._resetState();
  6717. var closeObserver = _this.closeObserver;
  6718. if (closeObserver) {
  6719. closeObserver.next(e);
  6720. }
  6721. if (e.wasClean) {
  6722. observer.complete();
  6723. }
  6724. else {
  6725. observer.error(e);
  6726. }
  6727. };
  6728. socket.onmessage = function (e) {
  6729. var result = tryCatch(_this.resultSelector)(e);
  6730. if (result === errorObject) {
  6731. observer.error(errorObject.e);
  6732. }
  6733. else {
  6734. observer.next(result);
  6735. }
  6736. };
  6737. };
  6738. /** @deprecated internal use only */ WebSocketSubject.prototype._subscribe = function (subscriber) {
  6739. var _this = this;
  6740. var source = this.source;
  6741. if (source) {
  6742. return source.subscribe(subscriber);
  6743. }
  6744. if (!this.socket) {
  6745. this._connectSocket();
  6746. }
  6747. var subscription = new Subscription();
  6748. subscription.add(this._output.subscribe(subscriber));
  6749. subscription.add(function () {
  6750. var socket = _this.socket;
  6751. if (_this._output.observers.length === 0) {
  6752. if (socket && socket.readyState === 1) {
  6753. socket.close();
  6754. }
  6755. _this._resetState();
  6756. }
  6757. });
  6758. return subscription;
  6759. };
  6760. WebSocketSubject.prototype.unsubscribe = function () {
  6761. var _a = this, source = _a.source, socket = _a.socket;
  6762. if (socket && socket.readyState === 1) {
  6763. socket.close();
  6764. this._resetState();
  6765. }
  6766. _super.prototype.unsubscribe.call(this);
  6767. if (!source) {
  6768. this.destination = new ReplaySubject();
  6769. }
  6770. };
  6771. return WebSocketSubject;
  6772. }(AnonymousSubject));
  6773. var webSocket = WebSocketSubject.create;
  6774. Observable.webSocket = webSocket;
  6775. /**
  6776. * Buffers the source Observable values until `closingNotifier` emits.
  6777. *
  6778. * <span class="informal">Collects values from the past as an array, and emits
  6779. * that array only when another Observable emits.</span>
  6780. *
  6781. * <img src="./img/buffer.png" width="100%">
  6782. *
  6783. * Buffers the incoming Observable values until the given `closingNotifier`
  6784. * Observable emits a value, at which point it emits the buffer on the output
  6785. * Observable and starts a new buffer internally, awaiting the next time
  6786. * `closingNotifier` emits.
  6787. *
  6788. * @example <caption>On every click, emit array of most recent interval events</caption>
  6789. * var clicks = Rx.Observable.fromEvent(document, 'click');
  6790. * var interval = Rx.Observable.interval(1000);
  6791. * var buffered = interval.buffer(clicks);
  6792. * buffered.subscribe(x => console.log(x));
  6793. *
  6794. * @see {@link bufferCount}
  6795. * @see {@link bufferTime}
  6796. * @see {@link bufferToggle}
  6797. * @see {@link bufferWhen}
  6798. * @see {@link window}
  6799. *
  6800. * @param {Observable<any>} closingNotifier An Observable that signals the
  6801. * buffer to be emitted on the output Observable.
  6802. * @return {Observable<T[]>} An Observable of buffers, which are arrays of
  6803. * values.
  6804. * @method buffer
  6805. * @owner Observable
  6806. */
  6807. function buffer$1(closingNotifier) {
  6808. return function bufferOperatorFunction(source) {
  6809. return source.lift(new BufferOperator(closingNotifier));
  6810. };
  6811. }
  6812. var BufferOperator = (function () {
  6813. function BufferOperator(closingNotifier) {
  6814. this.closingNotifier = closingNotifier;
  6815. }
  6816. BufferOperator.prototype.call = function (subscriber, source) {
  6817. return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
  6818. };
  6819. return BufferOperator;
  6820. }());
  6821. /**
  6822. * We need this JSDoc comment for affecting ESDoc.
  6823. * @ignore
  6824. * @extends {Ignored}
  6825. */
  6826. var BufferSubscriber = (function (_super) {
  6827. __extends(BufferSubscriber, _super);
  6828. function BufferSubscriber(destination, closingNotifier) {
  6829. _super.call(this, destination);
  6830. this.buffer = [];
  6831. this.add(subscribeToResult(this, closingNotifier));
  6832. }
  6833. BufferSubscriber.prototype._next = function (value) {
  6834. this.buffer.push(value);
  6835. };
  6836. BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  6837. var buffer = this.buffer;
  6838. this.buffer = [];
  6839. this.destination.next(buffer);
  6840. };
  6841. return BufferSubscriber;
  6842. }(OuterSubscriber));
  6843. /**
  6844. * Buffers the source Observable values until `closingNotifier` emits.
  6845. *
  6846. * <span class="informal">Collects values from the past as an array, and emits
  6847. * that array only when another Observable emits.</span>
  6848. *
  6849. * <img src="./img/buffer.png" width="100%">
  6850. *
  6851. * Buffers the incoming Observable values until the given `closingNotifier`
  6852. * Observable emits a value, at which point it emits the buffer on the output
  6853. * Observable and starts a new buffer internally, awaiting the next time
  6854. * `closingNotifier` emits.
  6855. *
  6856. * @example <caption>On every click, emit array of most recent interval events</caption>
  6857. * var clicks = Rx.Observable.fromEvent(document, 'click');
  6858. * var interval = Rx.Observable.interval(1000);
  6859. * var buffered = interval.buffer(clicks);
  6860. * buffered.subscribe(x => console.log(x));
  6861. *
  6862. * @see {@link bufferCount}
  6863. * @see {@link bufferTime}
  6864. * @see {@link bufferToggle}
  6865. * @see {@link bufferWhen}
  6866. * @see {@link window}
  6867. *
  6868. * @param {Observable<any>} closingNotifier An Observable that signals the
  6869. * buffer to be emitted on the output Observable.
  6870. * @return {Observable<T[]>} An Observable of buffers, which are arrays of
  6871. * values.
  6872. * @method buffer
  6873. * @owner Observable
  6874. */
  6875. function buffer$$1(closingNotifier) {
  6876. return buffer$1(closingNotifier)(this);
  6877. }
  6878. Observable.prototype.buffer = buffer$$1;
  6879. /**
  6880. * Buffers the source Observable values until the size hits the maximum
  6881. * `bufferSize` given.
  6882. *
  6883. * <span class="informal">Collects values from the past as an array, and emits
  6884. * that array only when its size reaches `bufferSize`.</span>
  6885. *
  6886. * <img src="./img/bufferCount.png" width="100%">
  6887. *
  6888. * Buffers a number of values from the source Observable by `bufferSize` then
  6889. * emits the buffer and clears it, and starts a new buffer each
  6890. * `startBufferEvery` values. If `startBufferEvery` is not provided or is
  6891. * `null`, then new buffers are started immediately at the start of the source
  6892. * and when each buffer closes and is emitted.
  6893. *
  6894. * @example <caption>Emit the last two click events as an array</caption>
  6895. * var clicks = Rx.Observable.fromEvent(document, 'click');
  6896. * var buffered = clicks.bufferCount(2);
  6897. * buffered.subscribe(x => console.log(x));
  6898. *
  6899. * @example <caption>On every click, emit the last two click events as an array</caption>
  6900. * var clicks = Rx.Observable.fromEvent(document, 'click');
  6901. * var buffered = clicks.bufferCount(2, 1);
  6902. * buffered.subscribe(x => console.log(x));
  6903. *
  6904. * @see {@link buffer}
  6905. * @see {@link bufferTime}
  6906. * @see {@link bufferToggle}
  6907. * @see {@link bufferWhen}
  6908. * @see {@link pairwise}
  6909. * @see {@link windowCount}
  6910. *
  6911. * @param {number} bufferSize The maximum size of the buffer emitted.
  6912. * @param {number} [startBufferEvery] Interval at which to start a new buffer.
  6913. * For example if `startBufferEvery` is `2`, then a new buffer will be started
  6914. * on every other value from the source. A new buffer is started at the
  6915. * beginning of the source by default.
  6916. * @return {Observable<T[]>} An Observable of arrays of buffered values.
  6917. * @method bufferCount
  6918. * @owner Observable
  6919. */
  6920. function bufferCount$1(bufferSize, startBufferEvery) {
  6921. if (startBufferEvery === void 0) { startBufferEvery = null; }
  6922. return function bufferCountOperatorFunction(source) {
  6923. return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
  6924. };
  6925. }
  6926. var BufferCountOperator = (function () {
  6927. function BufferCountOperator(bufferSize, startBufferEvery) {
  6928. this.bufferSize = bufferSize;
  6929. this.startBufferEvery = startBufferEvery;
  6930. if (!startBufferEvery || bufferSize === startBufferEvery) {
  6931. this.subscriberClass = BufferCountSubscriber;
  6932. }
  6933. else {
  6934. this.subscriberClass = BufferSkipCountSubscriber;
  6935. }
  6936. }
  6937. BufferCountOperator.prototype.call = function (subscriber, source) {
  6938. return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
  6939. };
  6940. return BufferCountOperator;
  6941. }());
  6942. /**
  6943. * We need this JSDoc comment for affecting ESDoc.
  6944. * @ignore
  6945. * @extends {Ignored}
  6946. */
  6947. var BufferCountSubscriber = (function (_super) {
  6948. __extends(BufferCountSubscriber, _super);
  6949. function BufferCountSubscriber(destination, bufferSize) {
  6950. _super.call(this, destination);
  6951. this.bufferSize = bufferSize;
  6952. this.buffer = [];
  6953. }
  6954. BufferCountSubscriber.prototype._next = function (value) {
  6955. var buffer = this.buffer;
  6956. buffer.push(value);
  6957. if (buffer.length == this.bufferSize) {
  6958. this.destination.next(buffer);
  6959. this.buffer = [];
  6960. }
  6961. };
  6962. BufferCountSubscriber.prototype._complete = function () {
  6963. var buffer = this.buffer;
  6964. if (buffer.length > 0) {
  6965. this.destination.next(buffer);
  6966. }
  6967. _super.prototype._complete.call(this);
  6968. };
  6969. return BufferCountSubscriber;
  6970. }(Subscriber));
  6971. /**
  6972. * We need this JSDoc comment for affecting ESDoc.
  6973. * @ignore
  6974. * @extends {Ignored}
  6975. */
  6976. var BufferSkipCountSubscriber = (function (_super) {
  6977. __extends(BufferSkipCountSubscriber, _super);
  6978. function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
  6979. _super.call(this, destination);
  6980. this.bufferSize = bufferSize;
  6981. this.startBufferEvery = startBufferEvery;
  6982. this.buffers = [];
  6983. this.count = 0;
  6984. }
  6985. BufferSkipCountSubscriber.prototype._next = function (value) {
  6986. var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
  6987. this.count++;
  6988. if (count % startBufferEvery === 0) {
  6989. buffers.push([]);
  6990. }
  6991. for (var i = buffers.length; i--;) {
  6992. var buffer = buffers[i];
  6993. buffer.push(value);
  6994. if (buffer.length === bufferSize) {
  6995. buffers.splice(i, 1);
  6996. this.destination.next(buffer);
  6997. }
  6998. }
  6999. };
  7000. BufferSkipCountSubscriber.prototype._complete = function () {
  7001. var _a = this, buffers = _a.buffers, destination = _a.destination;
  7002. while (buffers.length > 0) {
  7003. var buffer = buffers.shift();
  7004. if (buffer.length > 0) {
  7005. destination.next(buffer);
  7006. }
  7007. }
  7008. _super.prototype._complete.call(this);
  7009. };
  7010. return BufferSkipCountSubscriber;
  7011. }(Subscriber));
  7012. /**
  7013. * Buffers the source Observable values until the size hits the maximum
  7014. * `bufferSize` given.
  7015. *
  7016. * <span class="informal">Collects values from the past as an array, and emits
  7017. * that array only when its size reaches `bufferSize`.</span>
  7018. *
  7019. * <img src="./img/bufferCount.png" width="100%">
  7020. *
  7021. * Buffers a number of values from the source Observable by `bufferSize` then
  7022. * emits the buffer and clears it, and starts a new buffer each
  7023. * `startBufferEvery` values. If `startBufferEvery` is not provided or is
  7024. * `null`, then new buffers are started immediately at the start of the source
  7025. * and when each buffer closes and is emitted.
  7026. *
  7027. * @example <caption>Emit the last two click events as an array</caption>
  7028. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7029. * var buffered = clicks.bufferCount(2);
  7030. * buffered.subscribe(x => console.log(x));
  7031. *
  7032. * @example <caption>On every click, emit the last two click events as an array</caption>
  7033. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7034. * var buffered = clicks.bufferCount(2, 1);
  7035. * buffered.subscribe(x => console.log(x));
  7036. *
  7037. * @see {@link buffer}
  7038. * @see {@link bufferTime}
  7039. * @see {@link bufferToggle}
  7040. * @see {@link bufferWhen}
  7041. * @see {@link pairwise}
  7042. * @see {@link windowCount}
  7043. *
  7044. * @param {number} bufferSize The maximum size of the buffer emitted.
  7045. * @param {number} [startBufferEvery] Interval at which to start a new buffer.
  7046. * For example if `startBufferEvery` is `2`, then a new buffer will be started
  7047. * on every other value from the source. A new buffer is started at the
  7048. * beginning of the source by default.
  7049. * @return {Observable<T[]>} An Observable of arrays of buffered values.
  7050. * @method bufferCount
  7051. * @owner Observable
  7052. */
  7053. function bufferCount$$1(bufferSize, startBufferEvery) {
  7054. if (startBufferEvery === void 0) { startBufferEvery = null; }
  7055. return bufferCount$1(bufferSize, startBufferEvery)(this);
  7056. }
  7057. Observable.prototype.bufferCount = bufferCount$$1;
  7058. /* tslint:enable:max-line-length */
  7059. /**
  7060. * Buffers the source Observable values for a specific time period.
  7061. *
  7062. * <span class="informal">Collects values from the past as an array, and emits
  7063. * those arrays periodically in time.</span>
  7064. *
  7065. * <img src="./img/bufferTime.png" width="100%">
  7066. *
  7067. * Buffers values from the source for a specific time duration `bufferTimeSpan`.
  7068. * Unless the optional argument `bufferCreationInterval` is given, it emits and
  7069. * resets the buffer every `bufferTimeSpan` milliseconds. If
  7070. * `bufferCreationInterval` is given, this operator opens the buffer every
  7071. * `bufferCreationInterval` milliseconds and closes (emits and resets) the
  7072. * buffer every `bufferTimeSpan` milliseconds. When the optional argument
  7073. * `maxBufferSize` is specified, the buffer will be closed either after
  7074. * `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.
  7075. *
  7076. * @example <caption>Every second, emit an array of the recent click events</caption>
  7077. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7078. * var buffered = clicks.bufferTime(1000);
  7079. * buffered.subscribe(x => console.log(x));
  7080. *
  7081. * @example <caption>Every 5 seconds, emit the click events from the next 2 seconds</caption>
  7082. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7083. * var buffered = clicks.bufferTime(2000, 5000);
  7084. * buffered.subscribe(x => console.log(x));
  7085. *
  7086. * @see {@link buffer}
  7087. * @see {@link bufferCount}
  7088. * @see {@link bufferToggle}
  7089. * @see {@link bufferWhen}
  7090. * @see {@link windowTime}
  7091. *
  7092. * @param {number} bufferTimeSpan The amount of time to fill each buffer array.
  7093. * @param {number} [bufferCreationInterval] The interval at which to start new
  7094. * buffers.
  7095. * @param {number} [maxBufferSize] The maximum buffer size.
  7096. * @param {Scheduler} [scheduler=async] The scheduler on which to schedule the
  7097. * intervals that determine buffer boundaries.
  7098. * @return {Observable<T[]>} An observable of arrays of buffered values.
  7099. * @method bufferTime
  7100. * @owner Observable
  7101. */
  7102. function bufferTime$1(bufferTimeSpan) {
  7103. var length = arguments.length;
  7104. var scheduler = async;
  7105. if (isScheduler(arguments[arguments.length - 1])) {
  7106. scheduler = arguments[arguments.length - 1];
  7107. length--;
  7108. }
  7109. var bufferCreationInterval = null;
  7110. if (length >= 2) {
  7111. bufferCreationInterval = arguments[1];
  7112. }
  7113. var maxBufferSize = Number.POSITIVE_INFINITY;
  7114. if (length >= 3) {
  7115. maxBufferSize = arguments[2];
  7116. }
  7117. return function bufferTimeOperatorFunction(source) {
  7118. return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
  7119. };
  7120. }
  7121. var BufferTimeOperator = (function () {
  7122. function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
  7123. this.bufferTimeSpan = bufferTimeSpan;
  7124. this.bufferCreationInterval = bufferCreationInterval;
  7125. this.maxBufferSize = maxBufferSize;
  7126. this.scheduler = scheduler;
  7127. }
  7128. BufferTimeOperator.prototype.call = function (subscriber, source) {
  7129. return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
  7130. };
  7131. return BufferTimeOperator;
  7132. }());
  7133. var Context = (function () {
  7134. function Context() {
  7135. this.buffer = [];
  7136. }
  7137. return Context;
  7138. }());
  7139. /**
  7140. * We need this JSDoc comment for affecting ESDoc.
  7141. * @ignore
  7142. * @extends {Ignored}
  7143. */
  7144. var BufferTimeSubscriber = (function (_super) {
  7145. __extends(BufferTimeSubscriber, _super);
  7146. function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
  7147. _super.call(this, destination);
  7148. this.bufferTimeSpan = bufferTimeSpan;
  7149. this.bufferCreationInterval = bufferCreationInterval;
  7150. this.maxBufferSize = maxBufferSize;
  7151. this.scheduler = scheduler;
  7152. this.contexts = [];
  7153. var context = this.openContext();
  7154. this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
  7155. if (this.timespanOnly) {
  7156. var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
  7157. this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
  7158. }
  7159. else {
  7160. var closeState = { subscriber: this, context: context };
  7161. var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: this, scheduler: scheduler };
  7162. this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
  7163. this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
  7164. }
  7165. }
  7166. BufferTimeSubscriber.prototype._next = function (value) {
  7167. var contexts = this.contexts;
  7168. var len = contexts.length;
  7169. var filledBufferContext;
  7170. for (var i = 0; i < len; i++) {
  7171. var context = contexts[i];
  7172. var buffer = context.buffer;
  7173. buffer.push(value);
  7174. if (buffer.length == this.maxBufferSize) {
  7175. filledBufferContext = context;
  7176. }
  7177. }
  7178. if (filledBufferContext) {
  7179. this.onBufferFull(filledBufferContext);
  7180. }
  7181. };
  7182. BufferTimeSubscriber.prototype._error = function (err) {
  7183. this.contexts.length = 0;
  7184. _super.prototype._error.call(this, err);
  7185. };
  7186. BufferTimeSubscriber.prototype._complete = function () {
  7187. var _a = this, contexts = _a.contexts, destination = _a.destination;
  7188. while (contexts.length > 0) {
  7189. var context = contexts.shift();
  7190. destination.next(context.buffer);
  7191. }
  7192. _super.prototype._complete.call(this);
  7193. };
  7194. /** @deprecated internal use only */ BufferTimeSubscriber.prototype._unsubscribe = function () {
  7195. this.contexts = null;
  7196. };
  7197. BufferTimeSubscriber.prototype.onBufferFull = function (context) {
  7198. this.closeContext(context);
  7199. var closeAction = context.closeAction;
  7200. closeAction.unsubscribe();
  7201. this.remove(closeAction);
  7202. if (!this.closed && this.timespanOnly) {
  7203. context = this.openContext();
  7204. var bufferTimeSpan = this.bufferTimeSpan;
  7205. var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
  7206. this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
  7207. }
  7208. };
  7209. BufferTimeSubscriber.prototype.openContext = function () {
  7210. var context = new Context();
  7211. this.contexts.push(context);
  7212. return context;
  7213. };
  7214. BufferTimeSubscriber.prototype.closeContext = function (context) {
  7215. this.destination.next(context.buffer);
  7216. var contexts = this.contexts;
  7217. var spliceIndex = contexts ? contexts.indexOf(context) : -1;
  7218. if (spliceIndex >= 0) {
  7219. contexts.splice(contexts.indexOf(context), 1);
  7220. }
  7221. };
  7222. return BufferTimeSubscriber;
  7223. }(Subscriber));
  7224. function dispatchBufferTimeSpanOnly(state) {
  7225. var subscriber = state.subscriber;
  7226. var prevContext = state.context;
  7227. if (prevContext) {
  7228. subscriber.closeContext(prevContext);
  7229. }
  7230. if (!subscriber.closed) {
  7231. state.context = subscriber.openContext();
  7232. state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
  7233. }
  7234. }
  7235. function dispatchBufferCreation(state) {
  7236. var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler;
  7237. var context = subscriber.openContext();
  7238. var action = this;
  7239. if (!subscriber.closed) {
  7240. subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context }));
  7241. action.schedule(state, bufferCreationInterval);
  7242. }
  7243. }
  7244. function dispatchBufferClose(arg) {
  7245. var subscriber = arg.subscriber, context = arg.context;
  7246. subscriber.closeContext(context);
  7247. }
  7248. /* tslint:enable:max-line-length */
  7249. /**
  7250. * Buffers the source Observable values for a specific time period.
  7251. *
  7252. * <span class="informal">Collects values from the past as an array, and emits
  7253. * those arrays periodically in time.</span>
  7254. *
  7255. * <img src="./img/bufferTime.png" width="100%">
  7256. *
  7257. * Buffers values from the source for a specific time duration `bufferTimeSpan`.
  7258. * Unless the optional argument `bufferCreationInterval` is given, it emits and
  7259. * resets the buffer every `bufferTimeSpan` milliseconds. If
  7260. * `bufferCreationInterval` is given, this operator opens the buffer every
  7261. * `bufferCreationInterval` milliseconds and closes (emits and resets) the
  7262. * buffer every `bufferTimeSpan` milliseconds. When the optional argument
  7263. * `maxBufferSize` is specified, the buffer will be closed either after
  7264. * `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.
  7265. *
  7266. * @example <caption>Every second, emit an array of the recent click events</caption>
  7267. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7268. * var buffered = clicks.bufferTime(1000);
  7269. * buffered.subscribe(x => console.log(x));
  7270. *
  7271. * @example <caption>Every 5 seconds, emit the click events from the next 2 seconds</caption>
  7272. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7273. * var buffered = clicks.bufferTime(2000, 5000);
  7274. * buffered.subscribe(x => console.log(x));
  7275. *
  7276. * @see {@link buffer}
  7277. * @see {@link bufferCount}
  7278. * @see {@link bufferToggle}
  7279. * @see {@link bufferWhen}
  7280. * @see {@link windowTime}
  7281. *
  7282. * @param {number} bufferTimeSpan The amount of time to fill each buffer array.
  7283. * @param {number} [bufferCreationInterval] The interval at which to start new
  7284. * buffers.
  7285. * @param {number} [maxBufferSize] The maximum buffer size.
  7286. * @param {Scheduler} [scheduler=async] The scheduler on which to schedule the
  7287. * intervals that determine buffer boundaries.
  7288. * @return {Observable<T[]>} An observable of arrays of buffered values.
  7289. * @method bufferTime
  7290. * @owner Observable
  7291. */
  7292. function bufferTime$$1(bufferTimeSpan) {
  7293. var length = arguments.length;
  7294. var scheduler = async;
  7295. if (isScheduler(arguments[arguments.length - 1])) {
  7296. scheduler = arguments[arguments.length - 1];
  7297. length--;
  7298. }
  7299. var bufferCreationInterval = null;
  7300. if (length >= 2) {
  7301. bufferCreationInterval = arguments[1];
  7302. }
  7303. var maxBufferSize = Number.POSITIVE_INFINITY;
  7304. if (length >= 3) {
  7305. maxBufferSize = arguments[2];
  7306. }
  7307. return bufferTime$1(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler)(this);
  7308. }
  7309. Observable.prototype.bufferTime = bufferTime$$1;
  7310. /**
  7311. * Buffers the source Observable values starting from an emission from
  7312. * `openings` and ending when the output of `closingSelector` emits.
  7313. *
  7314. * <span class="informal">Collects values from the past as an array. Starts
  7315. * collecting only when `opening` emits, and calls the `closingSelector`
  7316. * function to get an Observable that tells when to close the buffer.</span>
  7317. *
  7318. * <img src="./img/bufferToggle.png" width="100%">
  7319. *
  7320. * Buffers values from the source by opening the buffer via signals from an
  7321. * Observable provided to `openings`, and closing and sending the buffers when
  7322. * a Subscribable or Promise returned by the `closingSelector` function emits.
  7323. *
  7324. * @example <caption>Every other second, emit the click events from the next 500ms</caption>
  7325. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7326. * var openings = Rx.Observable.interval(1000);
  7327. * var buffered = clicks.bufferToggle(openings, i =>
  7328. * i % 2 ? Rx.Observable.interval(500) : Rx.Observable.empty()
  7329. * );
  7330. * buffered.subscribe(x => console.log(x));
  7331. *
  7332. * @see {@link buffer}
  7333. * @see {@link bufferCount}
  7334. * @see {@link bufferTime}
  7335. * @see {@link bufferWhen}
  7336. * @see {@link windowToggle}
  7337. *
  7338. * @param {SubscribableOrPromise<O>} openings A Subscribable or Promise of notifications to start new
  7339. * buffers.
  7340. * @param {function(value: O): SubscribableOrPromise} closingSelector A function that takes
  7341. * the value emitted by the `openings` observable and returns a Subscribable or Promise,
  7342. * which, when it emits, signals that the associated buffer should be emitted
  7343. * and cleared.
  7344. * @return {Observable<T[]>} An observable of arrays of buffered values.
  7345. * @method bufferToggle
  7346. * @owner Observable
  7347. */
  7348. function bufferToggle$1(openings, closingSelector) {
  7349. return function bufferToggleOperatorFunction(source) {
  7350. return source.lift(new BufferToggleOperator(openings, closingSelector));
  7351. };
  7352. }
  7353. var BufferToggleOperator = (function () {
  7354. function BufferToggleOperator(openings, closingSelector) {
  7355. this.openings = openings;
  7356. this.closingSelector = closingSelector;
  7357. }
  7358. BufferToggleOperator.prototype.call = function (subscriber, source) {
  7359. return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
  7360. };
  7361. return BufferToggleOperator;
  7362. }());
  7363. /**
  7364. * We need this JSDoc comment for affecting ESDoc.
  7365. * @ignore
  7366. * @extends {Ignored}
  7367. */
  7368. var BufferToggleSubscriber = (function (_super) {
  7369. __extends(BufferToggleSubscriber, _super);
  7370. function BufferToggleSubscriber(destination, openings, closingSelector) {
  7371. _super.call(this, destination);
  7372. this.openings = openings;
  7373. this.closingSelector = closingSelector;
  7374. this.contexts = [];
  7375. this.add(subscribeToResult(this, openings));
  7376. }
  7377. BufferToggleSubscriber.prototype._next = function (value) {
  7378. var contexts = this.contexts;
  7379. var len = contexts.length;
  7380. for (var i = 0; i < len; i++) {
  7381. contexts[i].buffer.push(value);
  7382. }
  7383. };
  7384. BufferToggleSubscriber.prototype._error = function (err) {
  7385. var contexts = this.contexts;
  7386. while (contexts.length > 0) {
  7387. var context = contexts.shift();
  7388. context.subscription.unsubscribe();
  7389. context.buffer = null;
  7390. context.subscription = null;
  7391. }
  7392. this.contexts = null;
  7393. _super.prototype._error.call(this, err);
  7394. };
  7395. BufferToggleSubscriber.prototype._complete = function () {
  7396. var contexts = this.contexts;
  7397. while (contexts.length > 0) {
  7398. var context = contexts.shift();
  7399. this.destination.next(context.buffer);
  7400. context.subscription.unsubscribe();
  7401. context.buffer = null;
  7402. context.subscription = null;
  7403. }
  7404. this.contexts = null;
  7405. _super.prototype._complete.call(this);
  7406. };
  7407. BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  7408. outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
  7409. };
  7410. BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) {
  7411. this.closeBuffer(innerSub.context);
  7412. };
  7413. BufferToggleSubscriber.prototype.openBuffer = function (value) {
  7414. try {
  7415. var closingSelector = this.closingSelector;
  7416. var closingNotifier = closingSelector.call(this, value);
  7417. if (closingNotifier) {
  7418. this.trySubscribe(closingNotifier);
  7419. }
  7420. }
  7421. catch (err) {
  7422. this._error(err);
  7423. }
  7424. };
  7425. BufferToggleSubscriber.prototype.closeBuffer = function (context) {
  7426. var contexts = this.contexts;
  7427. if (contexts && context) {
  7428. var buffer = context.buffer, subscription = context.subscription;
  7429. this.destination.next(buffer);
  7430. contexts.splice(contexts.indexOf(context), 1);
  7431. this.remove(subscription);
  7432. subscription.unsubscribe();
  7433. }
  7434. };
  7435. BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) {
  7436. var contexts = this.contexts;
  7437. var buffer = [];
  7438. var subscription = new Subscription();
  7439. var context = { buffer: buffer, subscription: subscription };
  7440. contexts.push(context);
  7441. var innerSubscription = subscribeToResult(this, closingNotifier, context);
  7442. if (!innerSubscription || innerSubscription.closed) {
  7443. this.closeBuffer(context);
  7444. }
  7445. else {
  7446. innerSubscription.context = context;
  7447. this.add(innerSubscription);
  7448. subscription.add(innerSubscription);
  7449. }
  7450. };
  7451. return BufferToggleSubscriber;
  7452. }(OuterSubscriber));
  7453. /**
  7454. * Buffers the source Observable values starting from an emission from
  7455. * `openings` and ending when the output of `closingSelector` emits.
  7456. *
  7457. * <span class="informal">Collects values from the past as an array. Starts
  7458. * collecting only when `opening` emits, and calls the `closingSelector`
  7459. * function to get an Observable that tells when to close the buffer.</span>
  7460. *
  7461. * <img src="./img/bufferToggle.png" width="100%">
  7462. *
  7463. * Buffers values from the source by opening the buffer via signals from an
  7464. * Observable provided to `openings`, and closing and sending the buffers when
  7465. * a Subscribable or Promise returned by the `closingSelector` function emits.
  7466. *
  7467. * @example <caption>Every other second, emit the click events from the next 500ms</caption>
  7468. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7469. * var openings = Rx.Observable.interval(1000);
  7470. * var buffered = clicks.bufferToggle(openings, i =>
  7471. * i % 2 ? Rx.Observable.interval(500) : Rx.Observable.empty()
  7472. * );
  7473. * buffered.subscribe(x => console.log(x));
  7474. *
  7475. * @see {@link buffer}
  7476. * @see {@link bufferCount}
  7477. * @see {@link bufferTime}
  7478. * @see {@link bufferWhen}
  7479. * @see {@link windowToggle}
  7480. *
  7481. * @param {SubscribableOrPromise<O>} openings A Subscribable or Promise of notifications to start new
  7482. * buffers.
  7483. * @param {function(value: O): SubscribableOrPromise} closingSelector A function that takes
  7484. * the value emitted by the `openings` observable and returns a Subscribable or Promise,
  7485. * which, when it emits, signals that the associated buffer should be emitted
  7486. * and cleared.
  7487. * @return {Observable<T[]>} An observable of arrays of buffered values.
  7488. * @method bufferToggle
  7489. * @owner Observable
  7490. */
  7491. function bufferToggle$$1(openings, closingSelector) {
  7492. return bufferToggle$1(openings, closingSelector)(this);
  7493. }
  7494. Observable.prototype.bufferToggle = bufferToggle$$1;
  7495. /**
  7496. * Buffers the source Observable values, using a factory function of closing
  7497. * Observables to determine when to close, emit, and reset the buffer.
  7498. *
  7499. * <span class="informal">Collects values from the past as an array. When it
  7500. * starts collecting values, it calls a function that returns an Observable that
  7501. * tells when to close the buffer and restart collecting.</span>
  7502. *
  7503. * <img src="./img/bufferWhen.png" width="100%">
  7504. *
  7505. * Opens a buffer immediately, then closes the buffer when the observable
  7506. * returned by calling `closingSelector` function emits a value. When it closes
  7507. * the buffer, it immediately opens a new buffer and repeats the process.
  7508. *
  7509. * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
  7510. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7511. * var buffered = clicks.bufferWhen(() =>
  7512. * Rx.Observable.interval(1000 + Math.random() * 4000)
  7513. * );
  7514. * buffered.subscribe(x => console.log(x));
  7515. *
  7516. * @see {@link buffer}
  7517. * @see {@link bufferCount}
  7518. * @see {@link bufferTime}
  7519. * @see {@link bufferToggle}
  7520. * @see {@link windowWhen}
  7521. *
  7522. * @param {function(): Observable} closingSelector A function that takes no
  7523. * arguments and returns an Observable that signals buffer closure.
  7524. * @return {Observable<T[]>} An observable of arrays of buffered values.
  7525. * @method bufferWhen
  7526. * @owner Observable
  7527. */
  7528. function bufferWhen$1(closingSelector) {
  7529. return function (source) {
  7530. return source.lift(new BufferWhenOperator(closingSelector));
  7531. };
  7532. }
  7533. var BufferWhenOperator = (function () {
  7534. function BufferWhenOperator(closingSelector) {
  7535. this.closingSelector = closingSelector;
  7536. }
  7537. BufferWhenOperator.prototype.call = function (subscriber, source) {
  7538. return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
  7539. };
  7540. return BufferWhenOperator;
  7541. }());
  7542. /**
  7543. * We need this JSDoc comment for affecting ESDoc.
  7544. * @ignore
  7545. * @extends {Ignored}
  7546. */
  7547. var BufferWhenSubscriber = (function (_super) {
  7548. __extends(BufferWhenSubscriber, _super);
  7549. function BufferWhenSubscriber(destination, closingSelector) {
  7550. _super.call(this, destination);
  7551. this.closingSelector = closingSelector;
  7552. this.subscribing = false;
  7553. this.openBuffer();
  7554. }
  7555. BufferWhenSubscriber.prototype._next = function (value) {
  7556. this.buffer.push(value);
  7557. };
  7558. BufferWhenSubscriber.prototype._complete = function () {
  7559. var buffer = this.buffer;
  7560. if (buffer) {
  7561. this.destination.next(buffer);
  7562. }
  7563. _super.prototype._complete.call(this);
  7564. };
  7565. /** @deprecated internal use only */ BufferWhenSubscriber.prototype._unsubscribe = function () {
  7566. this.buffer = null;
  7567. this.subscribing = false;
  7568. };
  7569. BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  7570. this.openBuffer();
  7571. };
  7572. BufferWhenSubscriber.prototype.notifyComplete = function () {
  7573. if (this.subscribing) {
  7574. this.complete();
  7575. }
  7576. else {
  7577. this.openBuffer();
  7578. }
  7579. };
  7580. BufferWhenSubscriber.prototype.openBuffer = function () {
  7581. var closingSubscription = this.closingSubscription;
  7582. if (closingSubscription) {
  7583. this.remove(closingSubscription);
  7584. closingSubscription.unsubscribe();
  7585. }
  7586. var buffer = this.buffer;
  7587. if (this.buffer) {
  7588. this.destination.next(buffer);
  7589. }
  7590. this.buffer = [];
  7591. var closingNotifier = tryCatch(this.closingSelector)();
  7592. if (closingNotifier === errorObject) {
  7593. this.error(errorObject.e);
  7594. }
  7595. else {
  7596. closingSubscription = new Subscription();
  7597. this.closingSubscription = closingSubscription;
  7598. this.add(closingSubscription);
  7599. this.subscribing = true;
  7600. closingSubscription.add(subscribeToResult(this, closingNotifier));
  7601. this.subscribing = false;
  7602. }
  7603. };
  7604. return BufferWhenSubscriber;
  7605. }(OuterSubscriber));
  7606. /**
  7607. * Buffers the source Observable values, using a factory function of closing
  7608. * Observables to determine when to close, emit, and reset the buffer.
  7609. *
  7610. * <span class="informal">Collects values from the past as an array. When it
  7611. * starts collecting values, it calls a function that returns an Observable that
  7612. * tells when to close the buffer and restart collecting.</span>
  7613. *
  7614. * <img src="./img/bufferWhen.png" width="100%">
  7615. *
  7616. * Opens a buffer immediately, then closes the buffer when the observable
  7617. * returned by calling `closingSelector` function emits a value. When it closes
  7618. * the buffer, it immediately opens a new buffer and repeats the process.
  7619. *
  7620. * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
  7621. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7622. * var buffered = clicks.bufferWhen(() =>
  7623. * Rx.Observable.interval(1000 + Math.random() * 4000)
  7624. * );
  7625. * buffered.subscribe(x => console.log(x));
  7626. *
  7627. * @see {@link buffer}
  7628. * @see {@link bufferCount}
  7629. * @see {@link bufferTime}
  7630. * @see {@link bufferToggle}
  7631. * @see {@link windowWhen}
  7632. *
  7633. * @param {function(): Observable} closingSelector A function that takes no
  7634. * arguments and returns an Observable that signals buffer closure.
  7635. * @return {Observable<T[]>} An observable of arrays of buffered values.
  7636. * @method bufferWhen
  7637. * @owner Observable
  7638. */
  7639. function bufferWhen$$1(closingSelector) {
  7640. return bufferWhen$1(closingSelector)(this);
  7641. }
  7642. Observable.prototype.bufferWhen = bufferWhen$$1;
  7643. /**
  7644. * Catches errors on the observable to be handled by returning a new observable or throwing an error.
  7645. *
  7646. * <img src="./img/catch.png" width="100%">
  7647. *
  7648. * @example <caption>Continues with a different Observable when there's an error</caption>
  7649. *
  7650. * Observable.of(1, 2, 3, 4, 5)
  7651. * .map(n => {
  7652. * if (n == 4) {
  7653. * throw 'four!';
  7654. * }
  7655. * return n;
  7656. * })
  7657. * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
  7658. * .subscribe(x => console.log(x));
  7659. * // 1, 2, 3, I, II, III, IV, V
  7660. *
  7661. * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
  7662. *
  7663. * Observable.of(1, 2, 3, 4, 5)
  7664. * .map(n => {
  7665. * if (n === 4) {
  7666. * throw 'four!';
  7667. * }
  7668. * return n;
  7669. * })
  7670. * .catch((err, caught) => caught)
  7671. * .take(30)
  7672. * .subscribe(x => console.log(x));
  7673. * // 1, 2, 3, 1, 2, 3, ...
  7674. *
  7675. * @example <caption>Throws a new error when the source Observable throws an error</caption>
  7676. *
  7677. * Observable.of(1, 2, 3, 4, 5)
  7678. * .map(n => {
  7679. * if (n == 4) {
  7680. * throw 'four!';
  7681. * }
  7682. * return n;
  7683. * })
  7684. * .catch(err => {
  7685. * throw 'error in source. Details: ' + err;
  7686. * })
  7687. * .subscribe(
  7688. * x => console.log(x),
  7689. * err => console.log(err)
  7690. * );
  7691. * // 1, 2, 3, error in source. Details: four!
  7692. *
  7693. * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
  7694. * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
  7695. * is returned by the `selector` will be used to continue the observable chain.
  7696. * @return {Observable} An observable that originates from either the source or the observable returned by the
  7697. * catch `selector` function.
  7698. * @name catchError
  7699. */
  7700. function catchError(selector) {
  7701. return function catchErrorOperatorFunction(source) {
  7702. var operator = new CatchOperator(selector);
  7703. var caught = source.lift(operator);
  7704. return (operator.caught = caught);
  7705. };
  7706. }
  7707. var CatchOperator = (function () {
  7708. function CatchOperator(selector) {
  7709. this.selector = selector;
  7710. }
  7711. CatchOperator.prototype.call = function (subscriber, source) {
  7712. return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
  7713. };
  7714. return CatchOperator;
  7715. }());
  7716. /**
  7717. * We need this JSDoc comment for affecting ESDoc.
  7718. * @ignore
  7719. * @extends {Ignored}
  7720. */
  7721. var CatchSubscriber = (function (_super) {
  7722. __extends(CatchSubscriber, _super);
  7723. function CatchSubscriber(destination, selector, caught) {
  7724. _super.call(this, destination);
  7725. this.selector = selector;
  7726. this.caught = caught;
  7727. }
  7728. // NOTE: overriding `error` instead of `_error` because we don't want
  7729. // to have this flag this subscriber as `isStopped`. We can mimic the
  7730. // behavior of the RetrySubscriber (from the `retry` operator), where
  7731. // we unsubscribe from our source chain, reset our Subscriber flags,
  7732. // then subscribe to the selector result.
  7733. CatchSubscriber.prototype.error = function (err) {
  7734. if (!this.isStopped) {
  7735. var result = void 0;
  7736. try {
  7737. result = this.selector(err, this.caught);
  7738. }
  7739. catch (err2) {
  7740. _super.prototype.error.call(this, err2);
  7741. return;
  7742. }
  7743. this._unsubscribeAndRecycle();
  7744. this.add(subscribeToResult(this, result));
  7745. }
  7746. };
  7747. return CatchSubscriber;
  7748. }(OuterSubscriber));
  7749. /**
  7750. * Catches errors on the observable to be handled by returning a new observable or throwing an error.
  7751. *
  7752. * <img src="./img/catch.png" width="100%">
  7753. *
  7754. * @example <caption>Continues with a different Observable when there's an error</caption>
  7755. *
  7756. * Observable.of(1, 2, 3, 4, 5)
  7757. * .map(n => {
  7758. * if (n == 4) {
  7759. * throw 'four!';
  7760. * }
  7761. * return n;
  7762. * })
  7763. * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
  7764. * .subscribe(x => console.log(x));
  7765. * // 1, 2, 3, I, II, III, IV, V
  7766. *
  7767. * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
  7768. *
  7769. * Observable.of(1, 2, 3, 4, 5)
  7770. * .map(n => {
  7771. * if (n === 4) {
  7772. * throw 'four!';
  7773. * }
  7774. * return n;
  7775. * })
  7776. * .catch((err, caught) => caught)
  7777. * .take(30)
  7778. * .subscribe(x => console.log(x));
  7779. * // 1, 2, 3, 1, 2, 3, ...
  7780. *
  7781. * @example <caption>Throws a new error when the source Observable throws an error</caption>
  7782. *
  7783. * Observable.of(1, 2, 3, 4, 5)
  7784. * .map(n => {
  7785. * if (n == 4) {
  7786. * throw 'four!';
  7787. * }
  7788. * return n;
  7789. * })
  7790. * .catch(err => {
  7791. * throw 'error in source. Details: ' + err;
  7792. * })
  7793. * .subscribe(
  7794. * x => console.log(x),
  7795. * err => console.log(err)
  7796. * );
  7797. * // 1, 2, 3, error in source. Details: four!
  7798. *
  7799. * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
  7800. * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
  7801. * is returned by the `selector` will be used to continue the observable chain.
  7802. * @return {Observable} An observable that originates from either the source or the observable returned by the
  7803. * catch `selector` function.
  7804. * @method catch
  7805. * @name catch
  7806. * @owner Observable
  7807. */
  7808. function _catch(selector) {
  7809. return catchError(selector)(this);
  7810. }
  7811. Observable.prototype.catch = _catch;
  7812. Observable.prototype._catch = _catch;
  7813. function combineAll$1(project) {
  7814. return function (source) { return source.lift(new CombineLatestOperator(project)); };
  7815. }
  7816. /**
  7817. * Converts a higher-order Observable into a first-order Observable by waiting
  7818. * for the outer Observable to complete, then applying {@link combineLatest}.
  7819. *
  7820. * <span class="informal">Flattens an Observable-of-Observables by applying
  7821. * {@link combineLatest} when the Observable-of-Observables completes.</span>
  7822. *
  7823. * <img src="./img/combineAll.png" width="100%">
  7824. *
  7825. * Takes an Observable of Observables, and collects all Observables from it.
  7826. * Once the outer Observable completes, it subscribes to all collected
  7827. * Observables and combines their values using the {@link combineLatest}
  7828. * strategy, such that:
  7829. * - Every time an inner Observable emits, the output Observable emits.
  7830. * - When the returned observable emits, it emits all of the latest values by:
  7831. * - If a `project` function is provided, it is called with each recent value
  7832. * from each inner Observable in whatever order they arrived, and the result
  7833. * of the `project` function is what is emitted by the output Observable.
  7834. * - If there is no `project` function, an array of all of the most recent
  7835. * values is emitted by the output Observable.
  7836. *
  7837. * @example <caption>Map two click events to a finite interval Observable, then apply combineAll</caption>
  7838. * var clicks = Rx.Observable.fromEvent(document, 'click');
  7839. * var higherOrder = clicks.map(ev =>
  7840. * Rx.Observable.interval(Math.random()*2000).take(3)
  7841. * ).take(2);
  7842. * var result = higherOrder.combineAll();
  7843. * result.subscribe(x => console.log(x));
  7844. *
  7845. * @see {@link combineLatest}
  7846. * @see {@link mergeAll}
  7847. *
  7848. * @param {function} [project] An optional function to map the most recent
  7849. * values from each inner Observable into a new result. Takes each of the most
  7850. * recent values from each collected inner Observable as arguments, in order.
  7851. * @return {Observable} An Observable of projected results or arrays of recent
  7852. * values.
  7853. * @method combineAll
  7854. * @owner Observable
  7855. */
  7856. function combineAll$$1(project) {
  7857. return combineAll$1(project)(this);
  7858. }
  7859. Observable.prototype.combineAll = combineAll$$1;
  7860. /* tslint:enable:max-line-length */
  7861. /**
  7862. * Combines multiple Observables to create an Observable whose values are
  7863. * calculated from the latest values of each of its input Observables.
  7864. *
  7865. * <span class="informal">Whenever any input Observable emits a value, it
  7866. * computes a formula using the latest values from all the inputs, then emits
  7867. * the output of that formula.</span>
  7868. *
  7869. * <img src="./img/combineLatest.png" width="100%">
  7870. *
  7871. * `combineLatest` combines the values from this Observable with values from
  7872. * Observables passed as arguments. This is done by subscribing to each
  7873. * Observable, in order, and collecting an array of each of the most recent
  7874. * values any time any of the input Observables emits, then either taking that
  7875. * array and passing it as arguments to an optional `project` function and
  7876. * emitting the return value of that, or just emitting the array of recent
  7877. * values directly if there is no `project` function.
  7878. *
  7879. * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
  7880. * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
  7881. * var height = Rx.Observable.of(1.76, 1.77, 1.78);
  7882. * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
  7883. * bmi.subscribe(x => console.log('BMI is ' + x));
  7884. *
  7885. * // With output to console:
  7886. * // BMI is 24.212293388429753
  7887. * // BMI is 23.93948099205209
  7888. * // BMI is 23.671253629592222
  7889. *
  7890. * @see {@link combineAll}
  7891. * @see {@link merge}
  7892. * @see {@link withLatestFrom}
  7893. *
  7894. * @param {ObservableInput} other An input Observable to combine with the source
  7895. * Observable. More than one input Observables may be given as argument.
  7896. * @param {function} [project] An optional function to project the values from
  7897. * the combined latest values into a new value on the output Observable.
  7898. * @return {Observable} An Observable of projected values from the most recent
  7899. * values from each input Observable, or an array of the most recent values from
  7900. * each input Observable.
  7901. * @method combineLatest
  7902. * @owner Observable
  7903. */
  7904. function combineLatest$2() {
  7905. var observables = [];
  7906. for (var _i = 0; _i < arguments.length; _i++) {
  7907. observables[_i - 0] = arguments[_i];
  7908. }
  7909. return combineLatest$1.apply(void 0, observables)(this);
  7910. }
  7911. Observable.prototype.combineLatest = combineLatest$2;
  7912. /* tslint:enable:max-line-length */
  7913. /**
  7914. * Creates an output Observable which sequentially emits all values from every
  7915. * given input Observable after the current Observable.
  7916. *
  7917. * <span class="informal">Concatenates multiple Observables together by
  7918. * sequentially emitting their values, one Observable after the other.</span>
  7919. *
  7920. * <img src="./img/concat.png" width="100%">
  7921. *
  7922. * Joins this Observable with multiple other Observables by subscribing to them
  7923. * one at a time, starting with the source, and merging their results into the
  7924. * output Observable. Will wait for each Observable to complete before moving
  7925. * on to the next.
  7926. *
  7927. * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
  7928. * var timer = Rx.Observable.interval(1000).take(4);
  7929. * var sequence = Rx.Observable.range(1, 10);
  7930. * var result = timer.concat(sequence);
  7931. * result.subscribe(x => console.log(x));
  7932. *
  7933. * // results in:
  7934. * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
  7935. *
  7936. * @example <caption>Concatenate 3 Observables</caption>
  7937. * var timer1 = Rx.Observable.interval(1000).take(10);
  7938. * var timer2 = Rx.Observable.interval(2000).take(6);
  7939. * var timer3 = Rx.Observable.interval(500).take(10);
  7940. * var result = timer1.concat(timer2, timer3);
  7941. * result.subscribe(x => console.log(x));
  7942. *
  7943. * // results in the following:
  7944. * // (Prints to console sequentially)
  7945. * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
  7946. * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
  7947. * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
  7948. *
  7949. * @see {@link concatAll}
  7950. * @see {@link concatMap}
  7951. * @see {@link concatMapTo}
  7952. *
  7953. * @param {ObservableInput} other An input Observable to concatenate after the source
  7954. * Observable. More than one input Observables may be given as argument.
  7955. * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
  7956. * Observable subscription on.
  7957. * @return {Observable} All values of each passed Observable merged into a
  7958. * single Observable, in order, in serial fashion.
  7959. * @method concat
  7960. * @owner Observable
  7961. */
  7962. function concat$2() {
  7963. var observables = [];
  7964. for (var _i = 0; _i < arguments.length; _i++) {
  7965. observables[_i - 0] = arguments[_i];
  7966. }
  7967. return function (source) { return source.lift.call(concat.apply(void 0, [source].concat(observables))); };
  7968. }
  7969. /* tslint:enable:max-line-length */
  7970. /**
  7971. * Creates an output Observable which sequentially emits all values from every
  7972. * given input Observable after the current Observable.
  7973. *
  7974. * <span class="informal">Concatenates multiple Observables together by
  7975. * sequentially emitting their values, one Observable after the other.</span>
  7976. *
  7977. * <img src="./img/concat.png" width="100%">
  7978. *
  7979. * Joins this Observable with multiple other Observables by subscribing to them
  7980. * one at a time, starting with the source, and merging their results into the
  7981. * output Observable. Will wait for each Observable to complete before moving
  7982. * on to the next.
  7983. *
  7984. * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
  7985. * var timer = Rx.Observable.interval(1000).take(4);
  7986. * var sequence = Rx.Observable.range(1, 10);
  7987. * var result = timer.concat(sequence);
  7988. * result.subscribe(x => console.log(x));
  7989. *
  7990. * // results in:
  7991. * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
  7992. *
  7993. * @example <caption>Concatenate 3 Observables</caption>
  7994. * var timer1 = Rx.Observable.interval(1000).take(10);
  7995. * var timer2 = Rx.Observable.interval(2000).take(6);
  7996. * var timer3 = Rx.Observable.interval(500).take(10);
  7997. * var result = timer1.concat(timer2, timer3);
  7998. * result.subscribe(x => console.log(x));
  7999. *
  8000. * // results in the following:
  8001. * // (Prints to console sequentially)
  8002. * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
  8003. * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
  8004. * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
  8005. *
  8006. * @see {@link concatAll}
  8007. * @see {@link concatMap}
  8008. * @see {@link concatMapTo}
  8009. *
  8010. * @param {ObservableInput} other An input Observable to concatenate after the source
  8011. * Observable. More than one input Observables may be given as argument.
  8012. * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
  8013. * Observable subscription on.
  8014. * @return {Observable} All values of each passed Observable merged into a
  8015. * single Observable, in order, in serial fashion.
  8016. * @method concat
  8017. * @owner Observable
  8018. */
  8019. function concat$1() {
  8020. var observables = [];
  8021. for (var _i = 0; _i < arguments.length; _i++) {
  8022. observables[_i - 0] = arguments[_i];
  8023. }
  8024. return concat$2.apply(void 0, observables)(this);
  8025. }
  8026. Observable.prototype.concat = concat$1;
  8027. /* tslint:enable:max-line-length */
  8028. /**
  8029. * Converts a higher-order Observable into a first-order Observable by
  8030. * concatenating the inner Observables in order.
  8031. *
  8032. * <span class="informal">Flattens an Observable-of-Observables by putting one
  8033. * inner Observable after the other.</span>
  8034. *
  8035. * <img src="./img/concatAll.png" width="100%">
  8036. *
  8037. * Joins every Observable emitted by the source (a higher-order Observable), in
  8038. * a serial fashion. It subscribes to each inner Observable only after the
  8039. * previous inner Observable has completed, and merges all of their values into
  8040. * the returned observable.
  8041. *
  8042. * __Warning:__ If the source Observable emits Observables quickly and
  8043. * endlessly, and the inner Observables it emits generally complete slower than
  8044. * the source emits, you can run into memory issues as the incoming Observables
  8045. * collect in an unbounded buffer.
  8046. *
  8047. * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
  8048. * to `1`.
  8049. *
  8050. * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
  8051. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8052. * var higherOrder = clicks.map(ev => Rx.Observable.interval(1000).take(4));
  8053. * var firstOrder = higherOrder.concatAll();
  8054. * firstOrder.subscribe(x => console.log(x));
  8055. *
  8056. * // Results in the following:
  8057. * // (results are not concurrent)
  8058. * // For every click on the "document" it will emit values 0 to 3 spaced
  8059. * // on a 1000ms interval
  8060. * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
  8061. *
  8062. * @see {@link combineAll}
  8063. * @see {@link concat}
  8064. * @see {@link concatMap}
  8065. * @see {@link concatMapTo}
  8066. * @see {@link exhaust}
  8067. * @see {@link mergeAll}
  8068. * @see {@link switch}
  8069. * @see {@link zipAll}
  8070. *
  8071. * @return {Observable} An Observable emitting values from all the inner
  8072. * Observables concatenated.
  8073. * @method concatAll
  8074. * @owner Observable
  8075. */
  8076. function concatAll$1() {
  8077. return concatAll()(this);
  8078. }
  8079. Observable.prototype.concatAll = concatAll$1;
  8080. /* tslint:enable:max-line-length */
  8081. /**
  8082. * Projects each source value to an Observable which is merged in the output
  8083. * Observable, in a serialized fashion waiting for each one to complete before
  8084. * merging the next.
  8085. *
  8086. * <span class="informal">Maps each value to an Observable, then flattens all of
  8087. * these inner Observables using {@link concatAll}.</span>
  8088. *
  8089. * <img src="./img/concatMap.png" width="100%">
  8090. *
  8091. * Returns an Observable that emits items based on applying a function that you
  8092. * supply to each item emitted by the source Observable, where that function
  8093. * returns an (so-called "inner") Observable. Each new inner Observable is
  8094. * concatenated with the previous inner Observable.
  8095. *
  8096. * __Warning:__ if source values arrive endlessly and faster than their
  8097. * corresponding inner Observables can complete, it will result in memory issues
  8098. * as inner Observables amass in an unbounded buffer waiting for their turn to
  8099. * be subscribed to.
  8100. *
  8101. * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set
  8102. * to `1`.
  8103. *
  8104. * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
  8105. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8106. * var result = clicks.concatMap(ev => Rx.Observable.interval(1000).take(4));
  8107. * result.subscribe(x => console.log(x));
  8108. *
  8109. * // Results in the following:
  8110. * // (results are not concurrent)
  8111. * // For every click on the "document" it will emit values 0 to 3 spaced
  8112. * // on a 1000ms interval
  8113. * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
  8114. *
  8115. * @see {@link concat}
  8116. * @see {@link concatAll}
  8117. * @see {@link concatMapTo}
  8118. * @see {@link exhaustMap}
  8119. * @see {@link mergeMap}
  8120. * @see {@link switchMap}
  8121. *
  8122. * @param {function(value: T, ?index: number): ObservableInput} project A function
  8123. * that, when applied to an item emitted by the source Observable, returns an
  8124. * Observable.
  8125. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  8126. * A function to produce the value on the output Observable based on the values
  8127. * and the indices of the source (outer) emission and the inner Observable
  8128. * emission. The arguments passed to this function are:
  8129. * - `outerValue`: the value that came from the source
  8130. * - `innerValue`: the value that came from the projected Observable
  8131. * - `outerIndex`: the "index" of the value that came from the source
  8132. * - `innerIndex`: the "index" of the value from the projected Observable
  8133. * @return {Observable} An Observable that emits the result of applying the
  8134. * projection function (and the optional `resultSelector`) to each item emitted
  8135. * by the source Observable and taking values from each projected inner
  8136. * Observable sequentially.
  8137. * @method concatMap
  8138. * @owner Observable
  8139. */
  8140. function concatMap$1(project, resultSelector) {
  8141. return mergeMap(project, resultSelector, 1);
  8142. }
  8143. /* tslint:enable:max-line-length */
  8144. /**
  8145. * Projects each source value to an Observable which is merged in the output
  8146. * Observable, in a serialized fashion waiting for each one to complete before
  8147. * merging the next.
  8148. *
  8149. * <span class="informal">Maps each value to an Observable, then flattens all of
  8150. * these inner Observables using {@link concatAll}.</span>
  8151. *
  8152. * <img src="./img/concatMap.png" width="100%">
  8153. *
  8154. * Returns an Observable that emits items based on applying a function that you
  8155. * supply to each item emitted by the source Observable, where that function
  8156. * returns an (so-called "inner") Observable. Each new inner Observable is
  8157. * concatenated with the previous inner Observable.
  8158. *
  8159. * __Warning:__ if source values arrive endlessly and faster than their
  8160. * corresponding inner Observables can complete, it will result in memory issues
  8161. * as inner Observables amass in an unbounded buffer waiting for their turn to
  8162. * be subscribed to.
  8163. *
  8164. * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set
  8165. * to `1`.
  8166. *
  8167. * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
  8168. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8169. * var result = clicks.concatMap(ev => Rx.Observable.interval(1000).take(4));
  8170. * result.subscribe(x => console.log(x));
  8171. *
  8172. * // Results in the following:
  8173. * // (results are not concurrent)
  8174. * // For every click on the "document" it will emit values 0 to 3 spaced
  8175. * // on a 1000ms interval
  8176. * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
  8177. *
  8178. * @see {@link concat}
  8179. * @see {@link concatAll}
  8180. * @see {@link concatMapTo}
  8181. * @see {@link exhaustMap}
  8182. * @see {@link mergeMap}
  8183. * @see {@link switchMap}
  8184. *
  8185. * @param {function(value: T, ?index: number): ObservableInput} project A function
  8186. * that, when applied to an item emitted by the source Observable, returns an
  8187. * Observable.
  8188. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  8189. * A function to produce the value on the output Observable based on the values
  8190. * and the indices of the source (outer) emission and the inner Observable
  8191. * emission. The arguments passed to this function are:
  8192. * - `outerValue`: the value that came from the source
  8193. * - `innerValue`: the value that came from the projected Observable
  8194. * - `outerIndex`: the "index" of the value that came from the source
  8195. * - `innerIndex`: the "index" of the value from the projected Observable
  8196. * @return {Observable} An Observable that emits the result of applying the
  8197. * projection function (and the optional `resultSelector`) to each item emitted
  8198. * by the source Observable and taking values from each projected inner
  8199. * Observable sequentially.
  8200. * @method concatMap
  8201. * @owner Observable
  8202. */
  8203. function concatMap$$1(project, resultSelector) {
  8204. return concatMap$1(project, resultSelector)(this);
  8205. }
  8206. Observable.prototype.concatMap = concatMap$$1;
  8207. /* tslint:enable:max-line-length */
  8208. /**
  8209. * Projects each source value to the same Observable which is merged multiple
  8210. * times in a serialized fashion on the output Observable.
  8211. *
  8212. * <span class="informal">It's like {@link concatMap}, but maps each value
  8213. * always to the same inner Observable.</span>
  8214. *
  8215. * <img src="./img/concatMapTo.png" width="100%">
  8216. *
  8217. * Maps each source value to the given Observable `innerObservable` regardless
  8218. * of the source value, and then flattens those resulting Observables into one
  8219. * single Observable, which is the output Observable. Each new `innerObservable`
  8220. * instance emitted on the output Observable is concatenated with the previous
  8221. * `innerObservable` instance.
  8222. *
  8223. * __Warning:__ if source values arrive endlessly and faster than their
  8224. * corresponding inner Observables can complete, it will result in memory issues
  8225. * as inner Observables amass in an unbounded buffer waiting for their turn to
  8226. * be subscribed to.
  8227. *
  8228. * Note: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter
  8229. * set to `1`.
  8230. *
  8231. * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
  8232. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8233. * var result = clicks.concatMapTo(Rx.Observable.interval(1000).take(4));
  8234. * result.subscribe(x => console.log(x));
  8235. *
  8236. * // Results in the following:
  8237. * // (results are not concurrent)
  8238. * // For every click on the "document" it will emit values 0 to 3 spaced
  8239. * // on a 1000ms interval
  8240. * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
  8241. *
  8242. * @see {@link concat}
  8243. * @see {@link concatAll}
  8244. * @see {@link concatMap}
  8245. * @see {@link mergeMapTo}
  8246. * @see {@link switchMapTo}
  8247. *
  8248. * @param {ObservableInput} innerObservable An Observable to replace each value from
  8249. * the source Observable.
  8250. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  8251. * A function to produce the value on the output Observable based on the values
  8252. * and the indices of the source (outer) emission and the inner Observable
  8253. * emission. The arguments passed to this function are:
  8254. * - `outerValue`: the value that came from the source
  8255. * - `innerValue`: the value that came from the projected Observable
  8256. * - `outerIndex`: the "index" of the value that came from the source
  8257. * - `innerIndex`: the "index" of the value from the projected Observable
  8258. * @return {Observable} An observable of values merged together by joining the
  8259. * passed observable with itself, one after the other, for each value emitted
  8260. * from the source.
  8261. * @method concatMapTo
  8262. * @owner Observable
  8263. */
  8264. function concatMapTo$1(innerObservable, resultSelector) {
  8265. return concatMap$1(function () { return innerObservable; }, resultSelector);
  8266. }
  8267. /* tslint:enable:max-line-length */
  8268. /**
  8269. * Projects each source value to the same Observable which is merged multiple
  8270. * times in a serialized fashion on the output Observable.
  8271. *
  8272. * <span class="informal">It's like {@link concatMap}, but maps each value
  8273. * always to the same inner Observable.</span>
  8274. *
  8275. * <img src="./img/concatMapTo.png" width="100%">
  8276. *
  8277. * Maps each source value to the given Observable `innerObservable` regardless
  8278. * of the source value, and then flattens those resulting Observables into one
  8279. * single Observable, which is the output Observable. Each new `innerObservable`
  8280. * instance emitted on the output Observable is concatenated with the previous
  8281. * `innerObservable` instance.
  8282. *
  8283. * __Warning:__ if source values arrive endlessly and faster than their
  8284. * corresponding inner Observables can complete, it will result in memory issues
  8285. * as inner Observables amass in an unbounded buffer waiting for their turn to
  8286. * be subscribed to.
  8287. *
  8288. * Note: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter
  8289. * set to `1`.
  8290. *
  8291. * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
  8292. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8293. * var result = clicks.concatMapTo(Rx.Observable.interval(1000).take(4));
  8294. * result.subscribe(x => console.log(x));
  8295. *
  8296. * // Results in the following:
  8297. * // (results are not concurrent)
  8298. * // For every click on the "document" it will emit values 0 to 3 spaced
  8299. * // on a 1000ms interval
  8300. * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
  8301. *
  8302. * @see {@link concat}
  8303. * @see {@link concatAll}
  8304. * @see {@link concatMap}
  8305. * @see {@link mergeMapTo}
  8306. * @see {@link switchMapTo}
  8307. *
  8308. * @param {ObservableInput} innerObservable An Observable to replace each value from
  8309. * the source Observable.
  8310. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  8311. * A function to produce the value on the output Observable based on the values
  8312. * and the indices of the source (outer) emission and the inner Observable
  8313. * emission. The arguments passed to this function are:
  8314. * - `outerValue`: the value that came from the source
  8315. * - `innerValue`: the value that came from the projected Observable
  8316. * - `outerIndex`: the "index" of the value that came from the source
  8317. * - `innerIndex`: the "index" of the value from the projected Observable
  8318. * @return {Observable} An observable of values merged together by joining the
  8319. * passed observable with itself, one after the other, for each value emitted
  8320. * from the source.
  8321. * @method concatMapTo
  8322. * @owner Observable
  8323. */
  8324. function concatMapTo$$1(innerObservable, resultSelector) {
  8325. return concatMapTo$1(innerObservable, resultSelector)(this);
  8326. }
  8327. Observable.prototype.concatMapTo = concatMapTo$$1;
  8328. /**
  8329. * Counts the number of emissions on the source and emits that number when the
  8330. * source completes.
  8331. *
  8332. * <span class="informal">Tells how many values were emitted, when the source
  8333. * completes.</span>
  8334. *
  8335. * <img src="./img/count.png" width="100%">
  8336. *
  8337. * `count` transforms an Observable that emits values into an Observable that
  8338. * emits a single value that represents the number of values emitted by the
  8339. * source Observable. If the source Observable terminates with an error, `count`
  8340. * will pass this error notification along without emitting a value first. If
  8341. * the source Observable does not terminate at all, `count` will neither emit
  8342. * a value nor terminate. This operator takes an optional `predicate` function
  8343. * as argument, in which case the output emission will represent the number of
  8344. * source values that matched `true` with the `predicate`.
  8345. *
  8346. * @example <caption>Counts how many seconds have passed before the first click happened</caption>
  8347. * var seconds = Rx.Observable.interval(1000);
  8348. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8349. * var secondsBeforeClick = seconds.takeUntil(clicks);
  8350. * var result = secondsBeforeClick.count();
  8351. * result.subscribe(x => console.log(x));
  8352. *
  8353. * @example <caption>Counts how many odd numbers are there between 1 and 7</caption>
  8354. * var numbers = Rx.Observable.range(1, 7);
  8355. * var result = numbers.count(i => i % 2 === 1);
  8356. * result.subscribe(x => console.log(x));
  8357. *
  8358. * // Results in:
  8359. * // 4
  8360. *
  8361. * @see {@link max}
  8362. * @see {@link min}
  8363. * @see {@link reduce}
  8364. *
  8365. * @param {function(value: T, i: number, source: Observable<T>): boolean} [predicate] A
  8366. * boolean function to select what values are to be counted. It is provided with
  8367. * arguments of:
  8368. * - `value`: the value from the source Observable.
  8369. * - `index`: the (zero-based) "index" of the value from the source Observable.
  8370. * - `source`: the source Observable instance itself.
  8371. * @return {Observable} An Observable of one number that represents the count as
  8372. * described above.
  8373. * @method count
  8374. * @owner Observable
  8375. */
  8376. function count$1(predicate) {
  8377. return function (source) { return source.lift(new CountOperator(predicate, source)); };
  8378. }
  8379. var CountOperator = (function () {
  8380. function CountOperator(predicate, source) {
  8381. this.predicate = predicate;
  8382. this.source = source;
  8383. }
  8384. CountOperator.prototype.call = function (subscriber, source) {
  8385. return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
  8386. };
  8387. return CountOperator;
  8388. }());
  8389. /**
  8390. * We need this JSDoc comment for affecting ESDoc.
  8391. * @ignore
  8392. * @extends {Ignored}
  8393. */
  8394. var CountSubscriber = (function (_super) {
  8395. __extends(CountSubscriber, _super);
  8396. function CountSubscriber(destination, predicate, source) {
  8397. _super.call(this, destination);
  8398. this.predicate = predicate;
  8399. this.source = source;
  8400. this.count = 0;
  8401. this.index = 0;
  8402. }
  8403. CountSubscriber.prototype._next = function (value) {
  8404. if (this.predicate) {
  8405. this._tryPredicate(value);
  8406. }
  8407. else {
  8408. this.count++;
  8409. }
  8410. };
  8411. CountSubscriber.prototype._tryPredicate = function (value) {
  8412. var result;
  8413. try {
  8414. result = this.predicate(value, this.index++, this.source);
  8415. }
  8416. catch (err) {
  8417. this.destination.error(err);
  8418. return;
  8419. }
  8420. if (result) {
  8421. this.count++;
  8422. }
  8423. };
  8424. CountSubscriber.prototype._complete = function () {
  8425. this.destination.next(this.count);
  8426. this.destination.complete();
  8427. };
  8428. return CountSubscriber;
  8429. }(Subscriber));
  8430. /**
  8431. * Counts the number of emissions on the source and emits that number when the
  8432. * source completes.
  8433. *
  8434. * <span class="informal">Tells how many values were emitted, when the source
  8435. * completes.</span>
  8436. *
  8437. * <img src="./img/count.png" width="100%">
  8438. *
  8439. * `count` transforms an Observable that emits values into an Observable that
  8440. * emits a single value that represents the number of values emitted by the
  8441. * source Observable. If the source Observable terminates with an error, `count`
  8442. * will pass this error notification along without emitting a value first. If
  8443. * the source Observable does not terminate at all, `count` will neither emit
  8444. * a value nor terminate. This operator takes an optional `predicate` function
  8445. * as argument, in which case the output emission will represent the number of
  8446. * source values that matched `true` with the `predicate`.
  8447. *
  8448. * @example <caption>Counts how many seconds have passed before the first click happened</caption>
  8449. * var seconds = Rx.Observable.interval(1000);
  8450. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8451. * var secondsBeforeClick = seconds.takeUntil(clicks);
  8452. * var result = secondsBeforeClick.count();
  8453. * result.subscribe(x => console.log(x));
  8454. *
  8455. * @example <caption>Counts how many odd numbers are there between 1 and 7</caption>
  8456. * var numbers = Rx.Observable.range(1, 7);
  8457. * var result = numbers.count(i => i % 2 === 1);
  8458. * result.subscribe(x => console.log(x));
  8459. *
  8460. * // Results in:
  8461. * // 4
  8462. *
  8463. * @see {@link max}
  8464. * @see {@link min}
  8465. * @see {@link reduce}
  8466. *
  8467. * @param {function(value: T, i: number, source: Observable<T>): boolean} [predicate] A
  8468. * boolean function to select what values are to be counted. It is provided with
  8469. * arguments of:
  8470. * - `value`: the value from the source Observable.
  8471. * - `index`: the (zero-based) "index" of the value from the source Observable.
  8472. * - `source`: the source Observable instance itself.
  8473. * @return {Observable} An Observable of one number that represents the count as
  8474. * described above.
  8475. * @method count
  8476. * @owner Observable
  8477. */
  8478. function count$$1(predicate) {
  8479. return count$1(predicate)(this);
  8480. }
  8481. Observable.prototype.count = count$$1;
  8482. /**
  8483. * Converts an Observable of {@link Notification} objects into the emissions
  8484. * that they represent.
  8485. *
  8486. * <span class="informal">Unwraps {@link Notification} objects as actual `next`,
  8487. * `error` and `complete` emissions. The opposite of {@link materialize}.</span>
  8488. *
  8489. * <img src="./img/dematerialize.png" width="100%">
  8490. *
  8491. * `dematerialize` is assumed to operate an Observable that only emits
  8492. * {@link Notification} objects as `next` emissions, and does not emit any
  8493. * `error`. Such Observable is the output of a `materialize` operation. Those
  8494. * notifications are then unwrapped using the metadata they contain, and emitted
  8495. * as `next`, `error`, and `complete` on the output Observable.
  8496. *
  8497. * Use this operator in conjunction with {@link materialize}.
  8498. *
  8499. * @example <caption>Convert an Observable of Notifications to an actual Observable</caption>
  8500. * var notifA = new Rx.Notification('N', 'A');
  8501. * var notifB = new Rx.Notification('N', 'B');
  8502. * var notifE = new Rx.Notification('E', void 0,
  8503. * new TypeError('x.toUpperCase is not a function')
  8504. * );
  8505. * var materialized = Rx.Observable.of(notifA, notifB, notifE);
  8506. * var upperCase = materialized.dematerialize();
  8507. * upperCase.subscribe(x => console.log(x), e => console.error(e));
  8508. *
  8509. * // Results in:
  8510. * // A
  8511. * // B
  8512. * // TypeError: x.toUpperCase is not a function
  8513. *
  8514. * @see {@link Notification}
  8515. * @see {@link materialize}
  8516. *
  8517. * @return {Observable} An Observable that emits items and notifications
  8518. * embedded in Notification objects emitted by the source Observable.
  8519. * @method dematerialize
  8520. * @owner Observable
  8521. */
  8522. function dematerialize$1() {
  8523. return function dematerializeOperatorFunction(source) {
  8524. return source.lift(new DeMaterializeOperator());
  8525. };
  8526. }
  8527. var DeMaterializeOperator = (function () {
  8528. function DeMaterializeOperator() {
  8529. }
  8530. DeMaterializeOperator.prototype.call = function (subscriber, source) {
  8531. return source.subscribe(new DeMaterializeSubscriber(subscriber));
  8532. };
  8533. return DeMaterializeOperator;
  8534. }());
  8535. /**
  8536. * We need this JSDoc comment for affecting ESDoc.
  8537. * @ignore
  8538. * @extends {Ignored}
  8539. */
  8540. var DeMaterializeSubscriber = (function (_super) {
  8541. __extends(DeMaterializeSubscriber, _super);
  8542. function DeMaterializeSubscriber(destination) {
  8543. _super.call(this, destination);
  8544. }
  8545. DeMaterializeSubscriber.prototype._next = function (value) {
  8546. value.observe(this.destination);
  8547. };
  8548. return DeMaterializeSubscriber;
  8549. }(Subscriber));
  8550. /**
  8551. * Converts an Observable of {@link Notification} objects into the emissions
  8552. * that they represent.
  8553. *
  8554. * <span class="informal">Unwraps {@link Notification} objects as actual `next`,
  8555. * `error` and `complete` emissions. The opposite of {@link materialize}.</span>
  8556. *
  8557. * <img src="./img/dematerialize.png" width="100%">
  8558. *
  8559. * `dematerialize` is assumed to operate an Observable that only emits
  8560. * {@link Notification} objects as `next` emissions, and does not emit any
  8561. * `error`. Such Observable is the output of a `materialize` operation. Those
  8562. * notifications are then unwrapped using the metadata they contain, and emitted
  8563. * as `next`, `error`, and `complete` on the output Observable.
  8564. *
  8565. * Use this operator in conjunction with {@link materialize}.
  8566. *
  8567. * @example <caption>Convert an Observable of Notifications to an actual Observable</caption>
  8568. * var notifA = new Rx.Notification('N', 'A');
  8569. * var notifB = new Rx.Notification('N', 'B');
  8570. * var notifE = new Rx.Notification('E', void 0,
  8571. * new TypeError('x.toUpperCase is not a function')
  8572. * );
  8573. * var materialized = Rx.Observable.of(notifA, notifB, notifE);
  8574. * var upperCase = materialized.dematerialize();
  8575. * upperCase.subscribe(x => console.log(x), e => console.error(e));
  8576. *
  8577. * // Results in:
  8578. * // A
  8579. * // B
  8580. * // TypeError: x.toUpperCase is not a function
  8581. *
  8582. * @see {@link Notification}
  8583. * @see {@link materialize}
  8584. *
  8585. * @return {Observable} An Observable that emits items and notifications
  8586. * embedded in Notification objects emitted by the source Observable.
  8587. * @method dematerialize
  8588. * @owner Observable
  8589. */
  8590. function dematerialize$$1() {
  8591. return dematerialize$1()(this);
  8592. }
  8593. Observable.prototype.dematerialize = dematerialize$$1;
  8594. /**
  8595. * Emits a value from the source Observable only after a particular time span
  8596. * determined by another Observable has passed without another source emission.
  8597. *
  8598. * <span class="informal">It's like {@link debounceTime}, but the time span of
  8599. * emission silence is determined by a second Observable.</span>
  8600. *
  8601. * <img src="./img/debounce.png" width="100%">
  8602. *
  8603. * `debounce` delays values emitted by the source Observable, but drops previous
  8604. * pending delayed emissions if a new value arrives on the source Observable.
  8605. * This operator keeps track of the most recent value from the source
  8606. * Observable, and spawns a duration Observable by calling the
  8607. * `durationSelector` function. The value is emitted only when the duration
  8608. * Observable emits a value or completes, and if no other value was emitted on
  8609. * the source Observable since the duration Observable was spawned. If a new
  8610. * value appears before the duration Observable emits, the previous value will
  8611. * be dropped and will not be emitted on the output Observable.
  8612. *
  8613. * Like {@link debounceTime}, this is a rate-limiting operator, and also a
  8614. * delay-like operator since output emissions do not necessarily occur at the
  8615. * same time as they did on the source Observable.
  8616. *
  8617. * @example <caption>Emit the most recent click after a burst of clicks</caption>
  8618. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8619. * var result = clicks.debounce(() => Rx.Observable.interval(1000));
  8620. * result.subscribe(x => console.log(x));
  8621. *
  8622. * @see {@link audit}
  8623. * @see {@link debounceTime}
  8624. * @see {@link delayWhen}
  8625. * @see {@link throttle}
  8626. *
  8627. * @param {function(value: T): SubscribableOrPromise} durationSelector A function
  8628. * that receives a value from the source Observable, for computing the timeout
  8629. * duration for each source value, returned as an Observable or a Promise.
  8630. * @return {Observable} An Observable that delays the emissions of the source
  8631. * Observable by the specified duration Observable returned by
  8632. * `durationSelector`, and may drop some values if they occur too frequently.
  8633. * @method debounce
  8634. * @owner Observable
  8635. */
  8636. function debounce$1(durationSelector) {
  8637. return function (source) { return source.lift(new DebounceOperator(durationSelector)); };
  8638. }
  8639. var DebounceOperator = (function () {
  8640. function DebounceOperator(durationSelector) {
  8641. this.durationSelector = durationSelector;
  8642. }
  8643. DebounceOperator.prototype.call = function (subscriber, source) {
  8644. return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));
  8645. };
  8646. return DebounceOperator;
  8647. }());
  8648. /**
  8649. * We need this JSDoc comment for affecting ESDoc.
  8650. * @ignore
  8651. * @extends {Ignored}
  8652. */
  8653. var DebounceSubscriber = (function (_super) {
  8654. __extends(DebounceSubscriber, _super);
  8655. function DebounceSubscriber(destination, durationSelector) {
  8656. _super.call(this, destination);
  8657. this.durationSelector = durationSelector;
  8658. this.hasValue = false;
  8659. this.durationSubscription = null;
  8660. }
  8661. DebounceSubscriber.prototype._next = function (value) {
  8662. try {
  8663. var result = this.durationSelector.call(this, value);
  8664. if (result) {
  8665. this._tryNext(value, result);
  8666. }
  8667. }
  8668. catch (err) {
  8669. this.destination.error(err);
  8670. }
  8671. };
  8672. DebounceSubscriber.prototype._complete = function () {
  8673. this.emitValue();
  8674. this.destination.complete();
  8675. };
  8676. DebounceSubscriber.prototype._tryNext = function (value, duration) {
  8677. var subscription = this.durationSubscription;
  8678. this.value = value;
  8679. this.hasValue = true;
  8680. if (subscription) {
  8681. subscription.unsubscribe();
  8682. this.remove(subscription);
  8683. }
  8684. subscription = subscribeToResult(this, duration);
  8685. if (!subscription.closed) {
  8686. this.add(this.durationSubscription = subscription);
  8687. }
  8688. };
  8689. DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  8690. this.emitValue();
  8691. };
  8692. DebounceSubscriber.prototype.notifyComplete = function () {
  8693. this.emitValue();
  8694. };
  8695. DebounceSubscriber.prototype.emitValue = function () {
  8696. if (this.hasValue) {
  8697. var value = this.value;
  8698. var subscription = this.durationSubscription;
  8699. if (subscription) {
  8700. this.durationSubscription = null;
  8701. subscription.unsubscribe();
  8702. this.remove(subscription);
  8703. }
  8704. this.value = null;
  8705. this.hasValue = false;
  8706. _super.prototype._next.call(this, value);
  8707. }
  8708. };
  8709. return DebounceSubscriber;
  8710. }(OuterSubscriber));
  8711. /**
  8712. * Emits a value from the source Observable only after a particular time span
  8713. * determined by another Observable has passed without another source emission.
  8714. *
  8715. * <span class="informal">It's like {@link debounceTime}, but the time span of
  8716. * emission silence is determined by a second Observable.</span>
  8717. *
  8718. * <img src="./img/debounce.png" width="100%">
  8719. *
  8720. * `debounce` delays values emitted by the source Observable, but drops previous
  8721. * pending delayed emissions if a new value arrives on the source Observable.
  8722. * This operator keeps track of the most recent value from the source
  8723. * Observable, and spawns a duration Observable by calling the
  8724. * `durationSelector` function. The value is emitted only when the duration
  8725. * Observable emits a value or completes, and if no other value was emitted on
  8726. * the source Observable since the duration Observable was spawned. If a new
  8727. * value appears before the duration Observable emits, the previous value will
  8728. * be dropped and will not be emitted on the output Observable.
  8729. *
  8730. * Like {@link debounceTime}, this is a rate-limiting operator, and also a
  8731. * delay-like operator since output emissions do not necessarily occur at the
  8732. * same time as they did on the source Observable.
  8733. *
  8734. * @example <caption>Emit the most recent click after a burst of clicks</caption>
  8735. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8736. * var result = clicks.debounce(() => Rx.Observable.interval(1000));
  8737. * result.subscribe(x => console.log(x));
  8738. *
  8739. * @see {@link audit}
  8740. * @see {@link debounceTime}
  8741. * @see {@link delayWhen}
  8742. * @see {@link throttle}
  8743. *
  8744. * @param {function(value: T): SubscribableOrPromise} durationSelector A function
  8745. * that receives a value from the source Observable, for computing the timeout
  8746. * duration for each source value, returned as an Observable or a Promise.
  8747. * @return {Observable} An Observable that delays the emissions of the source
  8748. * Observable by the specified duration Observable returned by
  8749. * `durationSelector`, and may drop some values if they occur too frequently.
  8750. * @method debounce
  8751. * @owner Observable
  8752. */
  8753. function debounce$$1(durationSelector) {
  8754. return debounce$1(durationSelector)(this);
  8755. }
  8756. Observable.prototype.debounce = debounce$$1;
  8757. /**
  8758. * Emits a value from the source Observable only after a particular time span
  8759. * has passed without another source emission.
  8760. *
  8761. * <span class="informal">It's like {@link delay}, but passes only the most
  8762. * recent value from each burst of emissions.</span>
  8763. *
  8764. * <img src="./img/debounceTime.png" width="100%">
  8765. *
  8766. * `debounceTime` delays values emitted by the source Observable, but drops
  8767. * previous pending delayed emissions if a new value arrives on the source
  8768. * Observable. This operator keeps track of the most recent value from the
  8769. * source Observable, and emits that only when `dueTime` enough time has passed
  8770. * without any other value appearing on the source Observable. If a new value
  8771. * appears before `dueTime` silence occurs, the previous value will be dropped
  8772. * and will not be emitted on the output Observable.
  8773. *
  8774. * This is a rate-limiting operator, because it is impossible for more than one
  8775. * value to be emitted in any time window of duration `dueTime`, but it is also
  8776. * a delay-like operator since output emissions do not occur at the same time as
  8777. * they did on the source Observable. Optionally takes a {@link IScheduler} for
  8778. * managing timers.
  8779. *
  8780. * @example <caption>Emit the most recent click after a burst of clicks</caption>
  8781. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8782. * var result = clicks.debounceTime(1000);
  8783. * result.subscribe(x => console.log(x));
  8784. *
  8785. * @see {@link auditTime}
  8786. * @see {@link debounce}
  8787. * @see {@link delay}
  8788. * @see {@link sampleTime}
  8789. * @see {@link throttleTime}
  8790. *
  8791. * @param {number} dueTime The timeout duration in milliseconds (or the time
  8792. * unit determined internally by the optional `scheduler`) for the window of
  8793. * time required to wait for emission silence before emitting the most recent
  8794. * source value.
  8795. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  8796. * managing the timers that handle the timeout for each value.
  8797. * @return {Observable} An Observable that delays the emissions of the source
  8798. * Observable by the specified `dueTime`, and may drop some values if they occur
  8799. * too frequently.
  8800. * @method debounceTime
  8801. * @owner Observable
  8802. */
  8803. function debounceTime$1(dueTime, scheduler) {
  8804. if (scheduler === void 0) { scheduler = async; }
  8805. return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
  8806. }
  8807. var DebounceTimeOperator = (function () {
  8808. function DebounceTimeOperator(dueTime, scheduler) {
  8809. this.dueTime = dueTime;
  8810. this.scheduler = scheduler;
  8811. }
  8812. DebounceTimeOperator.prototype.call = function (subscriber, source) {
  8813. return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
  8814. };
  8815. return DebounceTimeOperator;
  8816. }());
  8817. /**
  8818. * We need this JSDoc comment for affecting ESDoc.
  8819. * @ignore
  8820. * @extends {Ignored}
  8821. */
  8822. var DebounceTimeSubscriber = (function (_super) {
  8823. __extends(DebounceTimeSubscriber, _super);
  8824. function DebounceTimeSubscriber(destination, dueTime, scheduler) {
  8825. _super.call(this, destination);
  8826. this.dueTime = dueTime;
  8827. this.scheduler = scheduler;
  8828. this.debouncedSubscription = null;
  8829. this.lastValue = null;
  8830. this.hasValue = false;
  8831. }
  8832. DebounceTimeSubscriber.prototype._next = function (value) {
  8833. this.clearDebounce();
  8834. this.lastValue = value;
  8835. this.hasValue = true;
  8836. this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext$3, this.dueTime, this));
  8837. };
  8838. DebounceTimeSubscriber.prototype._complete = function () {
  8839. this.debouncedNext();
  8840. this.destination.complete();
  8841. };
  8842. DebounceTimeSubscriber.prototype.debouncedNext = function () {
  8843. this.clearDebounce();
  8844. if (this.hasValue) {
  8845. this.destination.next(this.lastValue);
  8846. this.lastValue = null;
  8847. this.hasValue = false;
  8848. }
  8849. };
  8850. DebounceTimeSubscriber.prototype.clearDebounce = function () {
  8851. var debouncedSubscription = this.debouncedSubscription;
  8852. if (debouncedSubscription !== null) {
  8853. this.remove(debouncedSubscription);
  8854. debouncedSubscription.unsubscribe();
  8855. this.debouncedSubscription = null;
  8856. }
  8857. };
  8858. return DebounceTimeSubscriber;
  8859. }(Subscriber));
  8860. function dispatchNext$3(subscriber) {
  8861. subscriber.debouncedNext();
  8862. }
  8863. /**
  8864. * Emits a value from the source Observable only after a particular time span
  8865. * has passed without another source emission.
  8866. *
  8867. * <span class="informal">It's like {@link delay}, but passes only the most
  8868. * recent value from each burst of emissions.</span>
  8869. *
  8870. * <img src="./img/debounceTime.png" width="100%">
  8871. *
  8872. * `debounceTime` delays values emitted by the source Observable, but drops
  8873. * previous pending delayed emissions if a new value arrives on the source
  8874. * Observable. This operator keeps track of the most recent value from the
  8875. * source Observable, and emits that only when `dueTime` enough time has passed
  8876. * without any other value appearing on the source Observable. If a new value
  8877. * appears before `dueTime` silence occurs, the previous value will be dropped
  8878. * and will not be emitted on the output Observable.
  8879. *
  8880. * This is a rate-limiting operator, because it is impossible for more than one
  8881. * value to be emitted in any time window of duration `dueTime`, but it is also
  8882. * a delay-like operator since output emissions do not occur at the same time as
  8883. * they did on the source Observable. Optionally takes a {@link IScheduler} for
  8884. * managing timers.
  8885. *
  8886. * @example <caption>Emit the most recent click after a burst of clicks</caption>
  8887. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8888. * var result = clicks.debounceTime(1000);
  8889. * result.subscribe(x => console.log(x));
  8890. *
  8891. * @see {@link auditTime}
  8892. * @see {@link debounce}
  8893. * @see {@link delay}
  8894. * @see {@link sampleTime}
  8895. * @see {@link throttleTime}
  8896. *
  8897. * @param {number} dueTime The timeout duration in milliseconds (or the time
  8898. * unit determined internally by the optional `scheduler`) for the window of
  8899. * time required to wait for emission silence before emitting the most recent
  8900. * source value.
  8901. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  8902. * managing the timers that handle the timeout for each value.
  8903. * @return {Observable} An Observable that delays the emissions of the source
  8904. * Observable by the specified `dueTime`, and may drop some values if they occur
  8905. * too frequently.
  8906. * @method debounceTime
  8907. * @owner Observable
  8908. */
  8909. function debounceTime$$1(dueTime, scheduler) {
  8910. if (scheduler === void 0) { scheduler = async; }
  8911. return debounceTime$1(dueTime, scheduler)(this);
  8912. }
  8913. Observable.prototype.debounceTime = debounceTime$$1;
  8914. /* tslint:enable:max-line-length */
  8915. /**
  8916. * Emits a given value if the source Observable completes without emitting any
  8917. * `next` value, otherwise mirrors the source Observable.
  8918. *
  8919. * <span class="informal">If the source Observable turns out to be empty, then
  8920. * this operator will emit a default value.</span>
  8921. *
  8922. * <img src="./img/defaultIfEmpty.png" width="100%">
  8923. *
  8924. * `defaultIfEmpty` emits the values emitted by the source Observable or a
  8925. * specified default value if the source Observable is empty (completes without
  8926. * having emitted any `next` value).
  8927. *
  8928. * @example <caption>If no clicks happen in 5 seconds, then emit "no clicks"</caption>
  8929. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8930. * var clicksBeforeFive = clicks.takeUntil(Rx.Observable.interval(5000));
  8931. * var result = clicksBeforeFive.defaultIfEmpty('no clicks');
  8932. * result.subscribe(x => console.log(x));
  8933. *
  8934. * @see {@link empty}
  8935. * @see {@link last}
  8936. *
  8937. * @param {any} [defaultValue=null] The default value used if the source
  8938. * Observable is empty.
  8939. * @return {Observable} An Observable that emits either the specified
  8940. * `defaultValue` if the source Observable emits no items, or the values emitted
  8941. * by the source Observable.
  8942. * @method defaultIfEmpty
  8943. * @owner Observable
  8944. */
  8945. function defaultIfEmpty$1(defaultValue) {
  8946. if (defaultValue === void 0) { defaultValue = null; }
  8947. return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
  8948. }
  8949. var DefaultIfEmptyOperator = (function () {
  8950. function DefaultIfEmptyOperator(defaultValue) {
  8951. this.defaultValue = defaultValue;
  8952. }
  8953. DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
  8954. return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
  8955. };
  8956. return DefaultIfEmptyOperator;
  8957. }());
  8958. /**
  8959. * We need this JSDoc comment for affecting ESDoc.
  8960. * @ignore
  8961. * @extends {Ignored}
  8962. */
  8963. var DefaultIfEmptySubscriber = (function (_super) {
  8964. __extends(DefaultIfEmptySubscriber, _super);
  8965. function DefaultIfEmptySubscriber(destination, defaultValue) {
  8966. _super.call(this, destination);
  8967. this.defaultValue = defaultValue;
  8968. this.isEmpty = true;
  8969. }
  8970. DefaultIfEmptySubscriber.prototype._next = function (value) {
  8971. this.isEmpty = false;
  8972. this.destination.next(value);
  8973. };
  8974. DefaultIfEmptySubscriber.prototype._complete = function () {
  8975. if (this.isEmpty) {
  8976. this.destination.next(this.defaultValue);
  8977. }
  8978. this.destination.complete();
  8979. };
  8980. return DefaultIfEmptySubscriber;
  8981. }(Subscriber));
  8982. /* tslint:enable:max-line-length */
  8983. /**
  8984. * Emits a given value if the source Observable completes without emitting any
  8985. * `next` value, otherwise mirrors the source Observable.
  8986. *
  8987. * <span class="informal">If the source Observable turns out to be empty, then
  8988. * this operator will emit a default value.</span>
  8989. *
  8990. * <img src="./img/defaultIfEmpty.png" width="100%">
  8991. *
  8992. * `defaultIfEmpty` emits the values emitted by the source Observable or a
  8993. * specified default value if the source Observable is empty (completes without
  8994. * having emitted any `next` value).
  8995. *
  8996. * @example <caption>If no clicks happen in 5 seconds, then emit "no clicks"</caption>
  8997. * var clicks = Rx.Observable.fromEvent(document, 'click');
  8998. * var clicksBeforeFive = clicks.takeUntil(Rx.Observable.interval(5000));
  8999. * var result = clicksBeforeFive.defaultIfEmpty('no clicks');
  9000. * result.subscribe(x => console.log(x));
  9001. *
  9002. * @see {@link empty}
  9003. * @see {@link last}
  9004. *
  9005. * @param {any} [defaultValue=null] The default value used if the source
  9006. * Observable is empty.
  9007. * @return {Observable} An Observable that emits either the specified
  9008. * `defaultValue` if the source Observable emits no items, or the values emitted
  9009. * by the source Observable.
  9010. * @method defaultIfEmpty
  9011. * @owner Observable
  9012. */
  9013. function defaultIfEmpty$$1(defaultValue) {
  9014. if (defaultValue === void 0) { defaultValue = null; }
  9015. return defaultIfEmpty$1(defaultValue)(this);
  9016. }
  9017. Observable.prototype.defaultIfEmpty = defaultIfEmpty$$1;
  9018. /**
  9019. * Delays the emission of items from the source Observable by a given timeout or
  9020. * until a given Date.
  9021. *
  9022. * <span class="informal">Time shifts each item by some specified amount of
  9023. * milliseconds.</span>
  9024. *
  9025. * <img src="./img/delay.png" width="100%">
  9026. *
  9027. * If the delay argument is a Number, this operator time shifts the source
  9028. * Observable by that amount of time expressed in milliseconds. The relative
  9029. * time intervals between the values are preserved.
  9030. *
  9031. * If the delay argument is a Date, this operator time shifts the start of the
  9032. * Observable execution until the given date occurs.
  9033. *
  9034. * @example <caption>Delay each click by one second</caption>
  9035. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9036. * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
  9037. * delayedClicks.subscribe(x => console.log(x));
  9038. *
  9039. * @example <caption>Delay all clicks until a future date happens</caption>
  9040. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9041. * var date = new Date('March 15, 2050 12:00:00'); // in the future
  9042. * var delayedClicks = clicks.delay(date); // click emitted only after that date
  9043. * delayedClicks.subscribe(x => console.log(x));
  9044. *
  9045. * @see {@link debounceTime}
  9046. * @see {@link delayWhen}
  9047. *
  9048. * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
  9049. * a `Date` until which the emission of the source items is delayed.
  9050. * @param {Scheduler} [scheduler=async] The IScheduler to use for
  9051. * managing the timers that handle the time-shift for each item.
  9052. * @return {Observable} An Observable that delays the emissions of the source
  9053. * Observable by the specified timeout or Date.
  9054. * @method delay
  9055. * @owner Observable
  9056. */
  9057. function delay$1(delay, scheduler) {
  9058. if (scheduler === void 0) { scheduler = async; }
  9059. var absoluteDelay = isDate(delay);
  9060. var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
  9061. return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
  9062. }
  9063. var DelayOperator = (function () {
  9064. function DelayOperator(delay, scheduler) {
  9065. this.delay = delay;
  9066. this.scheduler = scheduler;
  9067. }
  9068. DelayOperator.prototype.call = function (subscriber, source) {
  9069. return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
  9070. };
  9071. return DelayOperator;
  9072. }());
  9073. /**
  9074. * We need this JSDoc comment for affecting ESDoc.
  9075. * @ignore
  9076. * @extends {Ignored}
  9077. */
  9078. var DelaySubscriber = (function (_super) {
  9079. __extends(DelaySubscriber, _super);
  9080. function DelaySubscriber(destination, delay, scheduler) {
  9081. _super.call(this, destination);
  9082. this.delay = delay;
  9083. this.scheduler = scheduler;
  9084. this.queue = [];
  9085. this.active = false;
  9086. this.errored = false;
  9087. }
  9088. DelaySubscriber.dispatch = function (state) {
  9089. var source = state.source;
  9090. var queue = source.queue;
  9091. var scheduler = state.scheduler;
  9092. var destination = state.destination;
  9093. while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
  9094. queue.shift().notification.observe(destination);
  9095. }
  9096. if (queue.length > 0) {
  9097. var delay_1 = Math.max(0, queue[0].time - scheduler.now());
  9098. this.schedule(state, delay_1);
  9099. }
  9100. else {
  9101. this.unsubscribe();
  9102. source.active = false;
  9103. }
  9104. };
  9105. DelaySubscriber.prototype._schedule = function (scheduler) {
  9106. this.active = true;
  9107. this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
  9108. source: this, destination: this.destination, scheduler: scheduler
  9109. }));
  9110. };
  9111. DelaySubscriber.prototype.scheduleNotification = function (notification) {
  9112. if (this.errored === true) {
  9113. return;
  9114. }
  9115. var scheduler = this.scheduler;
  9116. var message = new DelayMessage(scheduler.now() + this.delay, notification);
  9117. this.queue.push(message);
  9118. if (this.active === false) {
  9119. this._schedule(scheduler);
  9120. }
  9121. };
  9122. DelaySubscriber.prototype._next = function (value) {
  9123. this.scheduleNotification(Notification.createNext(value));
  9124. };
  9125. DelaySubscriber.prototype._error = function (err) {
  9126. this.errored = true;
  9127. this.queue = [];
  9128. this.destination.error(err);
  9129. };
  9130. DelaySubscriber.prototype._complete = function () {
  9131. this.scheduleNotification(Notification.createComplete());
  9132. };
  9133. return DelaySubscriber;
  9134. }(Subscriber));
  9135. var DelayMessage = (function () {
  9136. function DelayMessage(time, notification) {
  9137. this.time = time;
  9138. this.notification = notification;
  9139. }
  9140. return DelayMessage;
  9141. }());
  9142. /**
  9143. * Delays the emission of items from the source Observable by a given timeout or
  9144. * until a given Date.
  9145. *
  9146. * <span class="informal">Time shifts each item by some specified amount of
  9147. * milliseconds.</span>
  9148. *
  9149. * <img src="./img/delay.png" width="100%">
  9150. *
  9151. * If the delay argument is a Number, this operator time shifts the source
  9152. * Observable by that amount of time expressed in milliseconds. The relative
  9153. * time intervals between the values are preserved.
  9154. *
  9155. * If the delay argument is a Date, this operator time shifts the start of the
  9156. * Observable execution until the given date occurs.
  9157. *
  9158. * @example <caption>Delay each click by one second</caption>
  9159. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9160. * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
  9161. * delayedClicks.subscribe(x => console.log(x));
  9162. *
  9163. * @example <caption>Delay all clicks until a future date happens</caption>
  9164. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9165. * var date = new Date('March 15, 2050 12:00:00'); // in the future
  9166. * var delayedClicks = clicks.delay(date); // click emitted only after that date
  9167. * delayedClicks.subscribe(x => console.log(x));
  9168. *
  9169. * @see {@link debounceTime}
  9170. * @see {@link delayWhen}
  9171. *
  9172. * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
  9173. * a `Date` until which the emission of the source items is delayed.
  9174. * @param {Scheduler} [scheduler=async] The IScheduler to use for
  9175. * managing the timers that handle the time-shift for each item.
  9176. * @return {Observable} An Observable that delays the emissions of the source
  9177. * Observable by the specified timeout or Date.
  9178. * @method delay
  9179. * @owner Observable
  9180. */
  9181. function delay$$1(delay$$1, scheduler) {
  9182. if (scheduler === void 0) { scheduler = async; }
  9183. return delay$1(delay$$1, scheduler)(this);
  9184. }
  9185. Observable.prototype.delay = delay$$1;
  9186. /**
  9187. * Delays the emission of items from the source Observable by a given time span
  9188. * determined by the emissions of another Observable.
  9189. *
  9190. * <span class="informal">It's like {@link delay}, but the time span of the
  9191. * delay duration is determined by a second Observable.</span>
  9192. *
  9193. * <img src="./img/delayWhen.png" width="100%">
  9194. *
  9195. * `delayWhen` time shifts each emitted value from the source Observable by a
  9196. * time span determined by another Observable. When the source emits a value,
  9197. * the `delayDurationSelector` function is called with the source value as
  9198. * argument, and should return an Observable, called the "duration" Observable.
  9199. * The source value is emitted on the output Observable only when the duration
  9200. * Observable emits a value or completes.
  9201. *
  9202. * Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which
  9203. * is an Observable. When `subscriptionDelay` emits its first value or
  9204. * completes, the source Observable is subscribed to and starts behaving like
  9205. * described in the previous paragraph. If `subscriptionDelay` is not provided,
  9206. * `delayWhen` will subscribe to the source Observable as soon as the output
  9207. * Observable is subscribed.
  9208. *
  9209. * @example <caption>Delay each click by a random amount of time, between 0 and 5 seconds</caption>
  9210. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9211. * var delayedClicks = clicks.delayWhen(event =>
  9212. * Rx.Observable.interval(Math.random() * 5000)
  9213. * );
  9214. * delayedClicks.subscribe(x => console.log(x));
  9215. *
  9216. * @see {@link debounce}
  9217. * @see {@link delay}
  9218. *
  9219. * @param {function(value: T): Observable} delayDurationSelector A function that
  9220. * returns an Observable for each value emitted by the source Observable, which
  9221. * is then used to delay the emission of that item on the output Observable
  9222. * until the Observable returned from this function emits a value.
  9223. * @param {Observable} subscriptionDelay An Observable that triggers the
  9224. * subscription to the source Observable once it emits any value.
  9225. * @return {Observable} An Observable that delays the emissions of the source
  9226. * Observable by an amount of time specified by the Observable returned by
  9227. * `delayDurationSelector`.
  9228. * @method delayWhen
  9229. * @owner Observable
  9230. */
  9231. function delayWhen$1(delayDurationSelector, subscriptionDelay) {
  9232. if (subscriptionDelay) {
  9233. return function (source) {
  9234. return new SubscriptionDelayObservable(source, subscriptionDelay)
  9235. .lift(new DelayWhenOperator(delayDurationSelector));
  9236. };
  9237. }
  9238. return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); };
  9239. }
  9240. var DelayWhenOperator = (function () {
  9241. function DelayWhenOperator(delayDurationSelector) {
  9242. this.delayDurationSelector = delayDurationSelector;
  9243. }
  9244. DelayWhenOperator.prototype.call = function (subscriber, source) {
  9245. return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));
  9246. };
  9247. return DelayWhenOperator;
  9248. }());
  9249. /**
  9250. * We need this JSDoc comment for affecting ESDoc.
  9251. * @ignore
  9252. * @extends {Ignored}
  9253. */
  9254. var DelayWhenSubscriber = (function (_super) {
  9255. __extends(DelayWhenSubscriber, _super);
  9256. function DelayWhenSubscriber(destination, delayDurationSelector) {
  9257. _super.call(this, destination);
  9258. this.delayDurationSelector = delayDurationSelector;
  9259. this.completed = false;
  9260. this.delayNotifierSubscriptions = [];
  9261. this.values = [];
  9262. }
  9263. DelayWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  9264. this.destination.next(outerValue);
  9265. this.removeSubscription(innerSub);
  9266. this.tryComplete();
  9267. };
  9268. DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) {
  9269. this._error(error);
  9270. };
  9271. DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) {
  9272. var value = this.removeSubscription(innerSub);
  9273. if (value) {
  9274. this.destination.next(value);
  9275. }
  9276. this.tryComplete();
  9277. };
  9278. DelayWhenSubscriber.prototype._next = function (value) {
  9279. try {
  9280. var delayNotifier = this.delayDurationSelector(value);
  9281. if (delayNotifier) {
  9282. this.tryDelay(delayNotifier, value);
  9283. }
  9284. }
  9285. catch (err) {
  9286. this.destination.error(err);
  9287. }
  9288. };
  9289. DelayWhenSubscriber.prototype._complete = function () {
  9290. this.completed = true;
  9291. this.tryComplete();
  9292. };
  9293. DelayWhenSubscriber.prototype.removeSubscription = function (subscription) {
  9294. subscription.unsubscribe();
  9295. var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
  9296. var value = null;
  9297. if (subscriptionIdx !== -1) {
  9298. value = this.values[subscriptionIdx];
  9299. this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
  9300. this.values.splice(subscriptionIdx, 1);
  9301. }
  9302. return value;
  9303. };
  9304. DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) {
  9305. var notifierSubscription = subscribeToResult(this, delayNotifier, value);
  9306. if (notifierSubscription && !notifierSubscription.closed) {
  9307. this.add(notifierSubscription);
  9308. this.delayNotifierSubscriptions.push(notifierSubscription);
  9309. }
  9310. this.values.push(value);
  9311. };
  9312. DelayWhenSubscriber.prototype.tryComplete = function () {
  9313. if (this.completed && this.delayNotifierSubscriptions.length === 0) {
  9314. this.destination.complete();
  9315. }
  9316. };
  9317. return DelayWhenSubscriber;
  9318. }(OuterSubscriber));
  9319. /**
  9320. * We need this JSDoc comment for affecting ESDoc.
  9321. * @ignore
  9322. * @extends {Ignored}
  9323. */
  9324. var SubscriptionDelayObservable = (function (_super) {
  9325. __extends(SubscriptionDelayObservable, _super);
  9326. function SubscriptionDelayObservable(/** @deprecated internal use only */ source, subscriptionDelay) {
  9327. _super.call(this);
  9328. this.source = source;
  9329. this.subscriptionDelay = subscriptionDelay;
  9330. }
  9331. /** @deprecated internal use only */ SubscriptionDelayObservable.prototype._subscribe = function (subscriber) {
  9332. this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));
  9333. };
  9334. return SubscriptionDelayObservable;
  9335. }(Observable));
  9336. /**
  9337. * We need this JSDoc comment for affecting ESDoc.
  9338. * @ignore
  9339. * @extends {Ignored}
  9340. */
  9341. var SubscriptionDelaySubscriber = (function (_super) {
  9342. __extends(SubscriptionDelaySubscriber, _super);
  9343. function SubscriptionDelaySubscriber(parent, source) {
  9344. _super.call(this);
  9345. this.parent = parent;
  9346. this.source = source;
  9347. this.sourceSubscribed = false;
  9348. }
  9349. SubscriptionDelaySubscriber.prototype._next = function (unused) {
  9350. this.subscribeToSource();
  9351. };
  9352. SubscriptionDelaySubscriber.prototype._error = function (err) {
  9353. this.unsubscribe();
  9354. this.parent.error(err);
  9355. };
  9356. SubscriptionDelaySubscriber.prototype._complete = function () {
  9357. this.subscribeToSource();
  9358. };
  9359. SubscriptionDelaySubscriber.prototype.subscribeToSource = function () {
  9360. if (!this.sourceSubscribed) {
  9361. this.sourceSubscribed = true;
  9362. this.unsubscribe();
  9363. this.source.subscribe(this.parent);
  9364. }
  9365. };
  9366. return SubscriptionDelaySubscriber;
  9367. }(Subscriber));
  9368. /**
  9369. * Delays the emission of items from the source Observable by a given time span
  9370. * determined by the emissions of another Observable.
  9371. *
  9372. * <span class="informal">It's like {@link delay}, but the time span of the
  9373. * delay duration is determined by a second Observable.</span>
  9374. *
  9375. * <img src="./img/delayWhen.png" width="100%">
  9376. *
  9377. * `delayWhen` time shifts each emitted value from the source Observable by a
  9378. * time span determined by another Observable. When the source emits a value,
  9379. * the `delayDurationSelector` function is called with the source value as
  9380. * argument, and should return an Observable, called the "duration" Observable.
  9381. * The source value is emitted on the output Observable only when the duration
  9382. * Observable emits a value or completes.
  9383. *
  9384. * Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which
  9385. * is an Observable. When `subscriptionDelay` emits its first value or
  9386. * completes, the source Observable is subscribed to and starts behaving like
  9387. * described in the previous paragraph. If `subscriptionDelay` is not provided,
  9388. * `delayWhen` will subscribe to the source Observable as soon as the output
  9389. * Observable is subscribed.
  9390. *
  9391. * @example <caption>Delay each click by a random amount of time, between 0 and 5 seconds</caption>
  9392. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9393. * var delayedClicks = clicks.delayWhen(event =>
  9394. * Rx.Observable.interval(Math.random() * 5000)
  9395. * );
  9396. * delayedClicks.subscribe(x => console.log(x));
  9397. *
  9398. * @see {@link debounce}
  9399. * @see {@link delay}
  9400. *
  9401. * @param {function(value: T): Observable} delayDurationSelector A function that
  9402. * returns an Observable for each value emitted by the source Observable, which
  9403. * is then used to delay the emission of that item on the output Observable
  9404. * until the Observable returned from this function emits a value.
  9405. * @param {Observable} subscriptionDelay An Observable that triggers the
  9406. * subscription to the source Observable once it emits any value.
  9407. * @return {Observable} An Observable that delays the emissions of the source
  9408. * Observable by an amount of time specified by the Observable returned by
  9409. * `delayDurationSelector`.
  9410. * @method delayWhen
  9411. * @owner Observable
  9412. */
  9413. function delayWhen$$1(delayDurationSelector, subscriptionDelay) {
  9414. return delayWhen$1(delayDurationSelector, subscriptionDelay)(this);
  9415. }
  9416. Observable.prototype.delayWhen = delayWhen$$1;
  9417. function minimalSetImpl() {
  9418. // THIS IS NOT a full impl of Set, this is just the minimum
  9419. // bits of functionality we need for this library.
  9420. return (function () {
  9421. function MinimalSet() {
  9422. this._values = [];
  9423. }
  9424. MinimalSet.prototype.add = function (value) {
  9425. if (!this.has(value)) {
  9426. this._values.push(value);
  9427. }
  9428. };
  9429. MinimalSet.prototype.has = function (value) {
  9430. return this._values.indexOf(value) !== -1;
  9431. };
  9432. Object.defineProperty(MinimalSet.prototype, "size", {
  9433. get: function () {
  9434. return this._values.length;
  9435. },
  9436. enumerable: true,
  9437. configurable: true
  9438. });
  9439. MinimalSet.prototype.clear = function () {
  9440. this._values.length = 0;
  9441. };
  9442. return MinimalSet;
  9443. }());
  9444. }
  9445. var Set = _root.Set || minimalSetImpl();
  9446. /**
  9447. * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
  9448. *
  9449. * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
  9450. * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
  9451. * source observable directly with an equality check against previous values.
  9452. *
  9453. * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
  9454. *
  9455. * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
  9456. * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
  9457. * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
  9458. * that the internal `Set` can be "flushed", basically clearing it of values.
  9459. *
  9460. * @example <caption>A simple example with numbers</caption>
  9461. * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
  9462. * .distinct()
  9463. * .subscribe(x => console.log(x)); // 1, 2, 3, 4
  9464. *
  9465. * @example <caption>An example using a keySelector function</caption>
  9466. * interface Person {
  9467. * age: number,
  9468. * name: string
  9469. * }
  9470. *
  9471. * Observable.of<Person>(
  9472. * { age: 4, name: 'Foo'},
  9473. * { age: 7, name: 'Bar'},
  9474. * { age: 5, name: 'Foo'})
  9475. * .distinct((p: Person) => p.name)
  9476. * .subscribe(x => console.log(x));
  9477. *
  9478. * // displays:
  9479. * // { age: 4, name: 'Foo' }
  9480. * // { age: 7, name: 'Bar' }
  9481. *
  9482. * @see {@link distinctUntilChanged}
  9483. * @see {@link distinctUntilKeyChanged}
  9484. *
  9485. * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
  9486. * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
  9487. * @return {Observable} An Observable that emits items from the source Observable with distinct values.
  9488. * @method distinct
  9489. * @owner Observable
  9490. */
  9491. function distinct$1(keySelector, flushes) {
  9492. return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
  9493. }
  9494. var DistinctOperator = (function () {
  9495. function DistinctOperator(keySelector, flushes) {
  9496. this.keySelector = keySelector;
  9497. this.flushes = flushes;
  9498. }
  9499. DistinctOperator.prototype.call = function (subscriber, source) {
  9500. return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
  9501. };
  9502. return DistinctOperator;
  9503. }());
  9504. /**
  9505. * We need this JSDoc comment for affecting ESDoc.
  9506. * @ignore
  9507. * @extends {Ignored}
  9508. */
  9509. var DistinctSubscriber = (function (_super) {
  9510. __extends(DistinctSubscriber, _super);
  9511. function DistinctSubscriber(destination, keySelector, flushes) {
  9512. _super.call(this, destination);
  9513. this.keySelector = keySelector;
  9514. this.values = new Set();
  9515. if (flushes) {
  9516. this.add(subscribeToResult(this, flushes));
  9517. }
  9518. }
  9519. DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  9520. this.values.clear();
  9521. };
  9522. DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
  9523. this._error(error);
  9524. };
  9525. DistinctSubscriber.prototype._next = function (value) {
  9526. if (this.keySelector) {
  9527. this._useKeySelector(value);
  9528. }
  9529. else {
  9530. this._finalizeNext(value, value);
  9531. }
  9532. };
  9533. DistinctSubscriber.prototype._useKeySelector = function (value) {
  9534. var key;
  9535. var destination = this.destination;
  9536. try {
  9537. key = this.keySelector(value);
  9538. }
  9539. catch (err) {
  9540. destination.error(err);
  9541. return;
  9542. }
  9543. this._finalizeNext(key, value);
  9544. };
  9545. DistinctSubscriber.prototype._finalizeNext = function (key, value) {
  9546. var values = this.values;
  9547. if (!values.has(key)) {
  9548. values.add(key);
  9549. this.destination.next(value);
  9550. }
  9551. };
  9552. return DistinctSubscriber;
  9553. }(OuterSubscriber));
  9554. /**
  9555. * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
  9556. *
  9557. * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
  9558. * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
  9559. * source observable directly with an equality check against previous values.
  9560. *
  9561. * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
  9562. *
  9563. * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
  9564. * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
  9565. * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
  9566. * that the internal `Set` can be "flushed", basically clearing it of values.
  9567. *
  9568. * @example <caption>A simple example with numbers</caption>
  9569. * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
  9570. * .distinct()
  9571. * .subscribe(x => console.log(x)); // 1, 2, 3, 4
  9572. *
  9573. * @example <caption>An example using a keySelector function</caption>
  9574. * interface Person {
  9575. * age: number,
  9576. * name: string
  9577. * }
  9578. *
  9579. * Observable.of<Person>(
  9580. * { age: 4, name: 'Foo'},
  9581. * { age: 7, name: 'Bar'},
  9582. * { age: 5, name: 'Foo'})
  9583. * .distinct((p: Person) => p.name)
  9584. * .subscribe(x => console.log(x));
  9585. *
  9586. * // displays:
  9587. * // { age: 4, name: 'Foo' }
  9588. * // { age: 7, name: 'Bar' }
  9589. *
  9590. * @see {@link distinctUntilChanged}
  9591. * @see {@link distinctUntilKeyChanged}
  9592. *
  9593. * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
  9594. * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
  9595. * @return {Observable} An Observable that emits items from the source Observable with distinct values.
  9596. * @method distinct
  9597. * @owner Observable
  9598. */
  9599. function distinct$$1(keySelector, flushes) {
  9600. return distinct$1(keySelector, flushes)(this);
  9601. }
  9602. Observable.prototype.distinct = distinct$$1;
  9603. /* tslint:enable:max-line-length */
  9604. /**
  9605. * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
  9606. *
  9607. * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
  9608. *
  9609. * If a comparator function is not provided, an equality check is used by default.
  9610. *
  9611. * @example <caption>A simple example with numbers</caption>
  9612. * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
  9613. * .distinctUntilChanged()
  9614. * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
  9615. *
  9616. * @example <caption>An example using a compare function</caption>
  9617. * interface Person {
  9618. * age: number,
  9619. * name: string
  9620. * }
  9621. *
  9622. * Observable.of<Person>(
  9623. * { age: 4, name: 'Foo'},
  9624. * { age: 7, name: 'Bar'},
  9625. * { age: 5, name: 'Foo'})
  9626. * { age: 6, name: 'Foo'})
  9627. * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
  9628. * .subscribe(x => console.log(x));
  9629. *
  9630. * // displays:
  9631. * // { age: 4, name: 'Foo' }
  9632. * // { age: 7, name: 'Bar' }
  9633. * // { age: 5, name: 'Foo' }
  9634. *
  9635. * @see {@link distinct}
  9636. * @see {@link distinctUntilKeyChanged}
  9637. *
  9638. * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
  9639. * @return {Observable} An Observable that emits items from the source Observable with distinct values.
  9640. * @method distinctUntilChanged
  9641. * @owner Observable
  9642. */
  9643. function distinctUntilChanged$1(compare, keySelector) {
  9644. return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
  9645. }
  9646. var DistinctUntilChangedOperator = (function () {
  9647. function DistinctUntilChangedOperator(compare, keySelector) {
  9648. this.compare = compare;
  9649. this.keySelector = keySelector;
  9650. }
  9651. DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
  9652. return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
  9653. };
  9654. return DistinctUntilChangedOperator;
  9655. }());
  9656. /**
  9657. * We need this JSDoc comment for affecting ESDoc.
  9658. * @ignore
  9659. * @extends {Ignored}
  9660. */
  9661. var DistinctUntilChangedSubscriber = (function (_super) {
  9662. __extends(DistinctUntilChangedSubscriber, _super);
  9663. function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
  9664. _super.call(this, destination);
  9665. this.keySelector = keySelector;
  9666. this.hasKey = false;
  9667. if (typeof compare === 'function') {
  9668. this.compare = compare;
  9669. }
  9670. }
  9671. DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
  9672. return x === y;
  9673. };
  9674. DistinctUntilChangedSubscriber.prototype._next = function (value) {
  9675. var keySelector = this.keySelector;
  9676. var key = value;
  9677. if (keySelector) {
  9678. key = tryCatch(this.keySelector)(value);
  9679. if (key === errorObject) {
  9680. return this.destination.error(errorObject.e);
  9681. }
  9682. }
  9683. var result = false;
  9684. if (this.hasKey) {
  9685. result = tryCatch(this.compare)(this.key, key);
  9686. if (result === errorObject) {
  9687. return this.destination.error(errorObject.e);
  9688. }
  9689. }
  9690. else {
  9691. this.hasKey = true;
  9692. }
  9693. if (Boolean(result) === false) {
  9694. this.key = key;
  9695. this.destination.next(value);
  9696. }
  9697. };
  9698. return DistinctUntilChangedSubscriber;
  9699. }(Subscriber));
  9700. /* tslint:enable:max-line-length */
  9701. /**
  9702. * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
  9703. *
  9704. * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
  9705. *
  9706. * If a comparator function is not provided, an equality check is used by default.
  9707. *
  9708. * @example <caption>A simple example with numbers</caption>
  9709. * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
  9710. * .distinctUntilChanged()
  9711. * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
  9712. *
  9713. * @example <caption>An example using a compare function</caption>
  9714. * interface Person {
  9715. * age: number,
  9716. * name: string
  9717. * }
  9718. *
  9719. * Observable.of<Person>(
  9720. * { age: 4, name: 'Foo'},
  9721. * { age: 7, name: 'Bar'},
  9722. * { age: 5, name: 'Foo'})
  9723. * { age: 6, name: 'Foo'})
  9724. * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
  9725. * .subscribe(x => console.log(x));
  9726. *
  9727. * // displays:
  9728. * // { age: 4, name: 'Foo' }
  9729. * // { age: 7, name: 'Bar' }
  9730. * // { age: 5, name: 'Foo' }
  9731. *
  9732. * @see {@link distinct}
  9733. * @see {@link distinctUntilKeyChanged}
  9734. *
  9735. * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
  9736. * @return {Observable} An Observable that emits items from the source Observable with distinct values.
  9737. * @method distinctUntilChanged
  9738. * @owner Observable
  9739. */
  9740. function distinctUntilChanged$$1(compare, keySelector) {
  9741. return distinctUntilChanged$1(compare, keySelector)(this);
  9742. }
  9743. Observable.prototype.distinctUntilChanged = distinctUntilChanged$$1;
  9744. /* tslint:enable:max-line-length */
  9745. /**
  9746. * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item,
  9747. * using a property accessed by using the key provided to check if the two items are distinct.
  9748. *
  9749. * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
  9750. *
  9751. * If a comparator function is not provided, an equality check is used by default.
  9752. *
  9753. * @example <caption>An example comparing the name of persons</caption>
  9754. *
  9755. * interface Person {
  9756. * age: number,
  9757. * name: string
  9758. * }
  9759. *
  9760. * Observable.of<Person>(
  9761. * { age: 4, name: 'Foo'},
  9762. * { age: 7, name: 'Bar'},
  9763. * { age: 5, name: 'Foo'},
  9764. * { age: 6, name: 'Foo'})
  9765. * .distinctUntilKeyChanged('name')
  9766. * .subscribe(x => console.log(x));
  9767. *
  9768. * // displays:
  9769. * // { age: 4, name: 'Foo' }
  9770. * // { age: 7, name: 'Bar' }
  9771. * // { age: 5, name: 'Foo' }
  9772. *
  9773. * @example <caption>An example comparing the first letters of the name</caption>
  9774. *
  9775. * interface Person {
  9776. * age: number,
  9777. * name: string
  9778. * }
  9779. *
  9780. * Observable.of<Person>(
  9781. * { age: 4, name: 'Foo1'},
  9782. * { age: 7, name: 'Bar'},
  9783. * { age: 5, name: 'Foo2'},
  9784. * { age: 6, name: 'Foo3'})
  9785. * .distinctUntilKeyChanged('name', (x: string, y: string) => x.substring(0, 3) === y.substring(0, 3))
  9786. * .subscribe(x => console.log(x));
  9787. *
  9788. * // displays:
  9789. * // { age: 4, name: 'Foo1' }
  9790. * // { age: 7, name: 'Bar' }
  9791. * // { age: 5, name: 'Foo2' }
  9792. *
  9793. * @see {@link distinct}
  9794. * @see {@link distinctUntilChanged}
  9795. *
  9796. * @param {string} key String key for object property lookup on each item.
  9797. * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
  9798. * @return {Observable} An Observable that emits items from the source Observable with distinct values based on the key specified.
  9799. * @method distinctUntilKeyChanged
  9800. * @owner Observable
  9801. */
  9802. function distinctUntilKeyChanged$1(key, compare) {
  9803. return distinctUntilChanged$1(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; });
  9804. }
  9805. /* tslint:enable:max-line-length */
  9806. /**
  9807. * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item,
  9808. * using a property accessed by using the key provided to check if the two items are distinct.
  9809. *
  9810. * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
  9811. *
  9812. * If a comparator function is not provided, an equality check is used by default.
  9813. *
  9814. * @example <caption>An example comparing the name of persons</caption>
  9815. *
  9816. * interface Person {
  9817. * age: number,
  9818. * name: string
  9819. * }
  9820. *
  9821. * Observable.of<Person>(
  9822. * { age: 4, name: 'Foo'},
  9823. * { age: 7, name: 'Bar'},
  9824. * { age: 5, name: 'Foo'},
  9825. * { age: 6, name: 'Foo'})
  9826. * .distinctUntilKeyChanged('name')
  9827. * .subscribe(x => console.log(x));
  9828. *
  9829. * // displays:
  9830. * // { age: 4, name: 'Foo' }
  9831. * // { age: 7, name: 'Bar' }
  9832. * // { age: 5, name: 'Foo' }
  9833. *
  9834. * @example <caption>An example comparing the first letters of the name</caption>
  9835. *
  9836. * interface Person {
  9837. * age: number,
  9838. * name: string
  9839. * }
  9840. *
  9841. * Observable.of<Person>(
  9842. * { age: 4, name: 'Foo1'},
  9843. * { age: 7, name: 'Bar'},
  9844. * { age: 5, name: 'Foo2'},
  9845. * { age: 6, name: 'Foo3'})
  9846. * .distinctUntilKeyChanged('name', (x: string, y: string) => x.substring(0, 3) === y.substring(0, 3))
  9847. * .subscribe(x => console.log(x));
  9848. *
  9849. * // displays:
  9850. * // { age: 4, name: 'Foo1' }
  9851. * // { age: 7, name: 'Bar' }
  9852. * // { age: 5, name: 'Foo2' }
  9853. *
  9854. * @see {@link distinct}
  9855. * @see {@link distinctUntilChanged}
  9856. *
  9857. * @param {string} key String key for object property lookup on each item.
  9858. * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
  9859. * @return {Observable} An Observable that emits items from the source Observable with distinct values based on the key specified.
  9860. * @method distinctUntilKeyChanged
  9861. * @owner Observable
  9862. */
  9863. function distinctUntilKeyChanged$$1(key, compare) {
  9864. return distinctUntilKeyChanged$1(key, compare)(this);
  9865. }
  9866. Observable.prototype.distinctUntilKeyChanged = distinctUntilKeyChanged$$1;
  9867. /* tslint:enable:max-line-length */
  9868. /**
  9869. * Perform a side effect for every emission on the source Observable, but return
  9870. * an Observable that is identical to the source.
  9871. *
  9872. * <span class="informal">Intercepts each emission on the source and runs a
  9873. * function, but returns an output which is identical to the source as long as errors don't occur.</span>
  9874. *
  9875. * <img src="./img/do.png" width="100%">
  9876. *
  9877. * Returns a mirrored Observable of the source Observable, but modified so that
  9878. * the provided Observer is called to perform a side effect for every value,
  9879. * error, and completion emitted by the source. Any errors that are thrown in
  9880. * the aforementioned Observer or handlers are safely sent down the error path
  9881. * of the output Observable.
  9882. *
  9883. * This operator is useful for debugging your Observables for the correct values
  9884. * or performing other side effects.
  9885. *
  9886. * Note: this is different to a `subscribe` on the Observable. If the Observable
  9887. * returned by `do` is not subscribed, the side effects specified by the
  9888. * Observer will never happen. `do` therefore simply spies on existing
  9889. * execution, it does not trigger an execution to happen like `subscribe` does.
  9890. *
  9891. * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
  9892. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9893. * var positions = clicks
  9894. * .do(ev => console.log(ev))
  9895. * .map(ev => ev.clientX);
  9896. * positions.subscribe(x => console.log(x));
  9897. *
  9898. * @see {@link map}
  9899. * @see {@link subscribe}
  9900. *
  9901. * @param {Observer|function} [nextOrObserver] A normal Observer object or a
  9902. * callback for `next`.
  9903. * @param {function} [error] Callback for errors in the source.
  9904. * @param {function} [complete] Callback for the completion of the source.
  9905. * @return {Observable} An Observable identical to the source, but runs the
  9906. * specified Observer or callback(s) for each item.
  9907. * @name tap
  9908. */
  9909. function tap(nextOrObserver, error, complete) {
  9910. return function tapOperatorFunction(source) {
  9911. return source.lift(new DoOperator(nextOrObserver, error, complete));
  9912. };
  9913. }
  9914. var DoOperator = (function () {
  9915. function DoOperator(nextOrObserver, error, complete) {
  9916. this.nextOrObserver = nextOrObserver;
  9917. this.error = error;
  9918. this.complete = complete;
  9919. }
  9920. DoOperator.prototype.call = function (subscriber, source) {
  9921. return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
  9922. };
  9923. return DoOperator;
  9924. }());
  9925. /**
  9926. * We need this JSDoc comment for affecting ESDoc.
  9927. * @ignore
  9928. * @extends {Ignored}
  9929. */
  9930. var DoSubscriber = (function (_super) {
  9931. __extends(DoSubscriber, _super);
  9932. function DoSubscriber(destination, nextOrObserver, error, complete) {
  9933. _super.call(this, destination);
  9934. var safeSubscriber = new Subscriber(nextOrObserver, error, complete);
  9935. safeSubscriber.syncErrorThrowable = true;
  9936. this.add(safeSubscriber);
  9937. this.safeSubscriber = safeSubscriber;
  9938. }
  9939. DoSubscriber.prototype._next = function (value) {
  9940. var safeSubscriber = this.safeSubscriber;
  9941. safeSubscriber.next(value);
  9942. if (safeSubscriber.syncErrorThrown) {
  9943. this.destination.error(safeSubscriber.syncErrorValue);
  9944. }
  9945. else {
  9946. this.destination.next(value);
  9947. }
  9948. };
  9949. DoSubscriber.prototype._error = function (err) {
  9950. var safeSubscriber = this.safeSubscriber;
  9951. safeSubscriber.error(err);
  9952. if (safeSubscriber.syncErrorThrown) {
  9953. this.destination.error(safeSubscriber.syncErrorValue);
  9954. }
  9955. else {
  9956. this.destination.error(err);
  9957. }
  9958. };
  9959. DoSubscriber.prototype._complete = function () {
  9960. var safeSubscriber = this.safeSubscriber;
  9961. safeSubscriber.complete();
  9962. if (safeSubscriber.syncErrorThrown) {
  9963. this.destination.error(safeSubscriber.syncErrorValue);
  9964. }
  9965. else {
  9966. this.destination.complete();
  9967. }
  9968. };
  9969. return DoSubscriber;
  9970. }(Subscriber));
  9971. /* tslint:enable:max-line-length */
  9972. /**
  9973. * Perform a side effect for every emission on the source Observable, but return
  9974. * an Observable that is identical to the source.
  9975. *
  9976. * <span class="informal">Intercepts each emission on the source and runs a
  9977. * function, but returns an output which is identical to the source as long as errors don't occur.</span>
  9978. *
  9979. * <img src="./img/do.png" width="100%">
  9980. *
  9981. * Returns a mirrored Observable of the source Observable, but modified so that
  9982. * the provided Observer is called to perform a side effect for every value,
  9983. * error, and completion emitted by the source. Any errors that are thrown in
  9984. * the aforementioned Observer or handlers are safely sent down the error path
  9985. * of the output Observable.
  9986. *
  9987. * This operator is useful for debugging your Observables for the correct values
  9988. * or performing other side effects.
  9989. *
  9990. * Note: this is different to a `subscribe` on the Observable. If the Observable
  9991. * returned by `do` is not subscribed, the side effects specified by the
  9992. * Observer will never happen. `do` therefore simply spies on existing
  9993. * execution, it does not trigger an execution to happen like `subscribe` does.
  9994. *
  9995. * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
  9996. * var clicks = Rx.Observable.fromEvent(document, 'click');
  9997. * var positions = clicks
  9998. * .do(ev => console.log(ev))
  9999. * .map(ev => ev.clientX);
  10000. * positions.subscribe(x => console.log(x));
  10001. *
  10002. * @see {@link map}
  10003. * @see {@link subscribe}
  10004. *
  10005. * @param {Observer|function} [nextOrObserver] A normal Observer object or a
  10006. * callback for `next`.
  10007. * @param {function} [error] Callback for errors in the source.
  10008. * @param {function} [complete] Callback for the completion of the source.
  10009. * @return {Observable} An Observable identical to the source, but runs the
  10010. * specified Observer or callback(s) for each item.
  10011. * @method do
  10012. * @name do
  10013. * @owner Observable
  10014. */
  10015. function _do(nextOrObserver, error, complete) {
  10016. return tap(nextOrObserver, error, complete)(this);
  10017. }
  10018. Observable.prototype.do = _do;
  10019. Observable.prototype._do = _do;
  10020. /**
  10021. * Converts a higher-order Observable into a first-order Observable by dropping
  10022. * inner Observables while the previous inner Observable has not yet completed.
  10023. *
  10024. * <span class="informal">Flattens an Observable-of-Observables by dropping the
  10025. * next inner Observables while the current inner is still executing.</span>
  10026. *
  10027. * <img src="./img/exhaust.png" width="100%">
  10028. *
  10029. * `exhaust` subscribes to an Observable that emits Observables, also known as a
  10030. * higher-order Observable. Each time it observes one of these emitted inner
  10031. * Observables, the output Observable begins emitting the items emitted by that
  10032. * inner Observable. So far, it behaves like {@link mergeAll}. However,
  10033. * `exhaust` ignores every new inner Observable if the previous Observable has
  10034. * not yet completed. Once that one completes, it will accept and flatten the
  10035. * next inner Observable and repeat this process.
  10036. *
  10037. * @example <caption>Run a finite timer for each click, only if there is no currently active timer</caption>
  10038. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10039. * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(5));
  10040. * var result = higherOrder.exhaust();
  10041. * result.subscribe(x => console.log(x));
  10042. *
  10043. * @see {@link combineAll}
  10044. * @see {@link concatAll}
  10045. * @see {@link switch}
  10046. * @see {@link mergeAll}
  10047. * @see {@link exhaustMap}
  10048. * @see {@link zipAll}
  10049. *
  10050. * @return {Observable} An Observable that takes a source of Observables and propagates the first observable
  10051. * exclusively until it completes before subscribing to the next.
  10052. * @method exhaust
  10053. * @owner Observable
  10054. */
  10055. function exhaust$1() {
  10056. return function (source) { return source.lift(new SwitchFirstOperator()); };
  10057. }
  10058. var SwitchFirstOperator = (function () {
  10059. function SwitchFirstOperator() {
  10060. }
  10061. SwitchFirstOperator.prototype.call = function (subscriber, source) {
  10062. return source.subscribe(new SwitchFirstSubscriber(subscriber));
  10063. };
  10064. return SwitchFirstOperator;
  10065. }());
  10066. /**
  10067. * We need this JSDoc comment for affecting ESDoc.
  10068. * @ignore
  10069. * @extends {Ignored}
  10070. */
  10071. var SwitchFirstSubscriber = (function (_super) {
  10072. __extends(SwitchFirstSubscriber, _super);
  10073. function SwitchFirstSubscriber(destination) {
  10074. _super.call(this, destination);
  10075. this.hasCompleted = false;
  10076. this.hasSubscription = false;
  10077. }
  10078. SwitchFirstSubscriber.prototype._next = function (value) {
  10079. if (!this.hasSubscription) {
  10080. this.hasSubscription = true;
  10081. this.add(subscribeToResult(this, value));
  10082. }
  10083. };
  10084. SwitchFirstSubscriber.prototype._complete = function () {
  10085. this.hasCompleted = true;
  10086. if (!this.hasSubscription) {
  10087. this.destination.complete();
  10088. }
  10089. };
  10090. SwitchFirstSubscriber.prototype.notifyComplete = function (innerSub) {
  10091. this.remove(innerSub);
  10092. this.hasSubscription = false;
  10093. if (this.hasCompleted) {
  10094. this.destination.complete();
  10095. }
  10096. };
  10097. return SwitchFirstSubscriber;
  10098. }(OuterSubscriber));
  10099. /**
  10100. * Converts a higher-order Observable into a first-order Observable by dropping
  10101. * inner Observables while the previous inner Observable has not yet completed.
  10102. *
  10103. * <span class="informal">Flattens an Observable-of-Observables by dropping the
  10104. * next inner Observables while the current inner is still executing.</span>
  10105. *
  10106. * <img src="./img/exhaust.png" width="100%">
  10107. *
  10108. * `exhaust` subscribes to an Observable that emits Observables, also known as a
  10109. * higher-order Observable. Each time it observes one of these emitted inner
  10110. * Observables, the output Observable begins emitting the items emitted by that
  10111. * inner Observable. So far, it behaves like {@link mergeAll}. However,
  10112. * `exhaust` ignores every new inner Observable if the previous Observable has
  10113. * not yet completed. Once that one completes, it will accept and flatten the
  10114. * next inner Observable and repeat this process.
  10115. *
  10116. * @example <caption>Run a finite timer for each click, only if there is no currently active timer</caption>
  10117. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10118. * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(5));
  10119. * var result = higherOrder.exhaust();
  10120. * result.subscribe(x => console.log(x));
  10121. *
  10122. * @see {@link combineAll}
  10123. * @see {@link concatAll}
  10124. * @see {@link switch}
  10125. * @see {@link mergeAll}
  10126. * @see {@link exhaustMap}
  10127. * @see {@link zipAll}
  10128. *
  10129. * @return {Observable} An Observable that takes a source of Observables and propagates the first observable
  10130. * exclusively until it completes before subscribing to the next.
  10131. * @method exhaust
  10132. * @owner Observable
  10133. */
  10134. function exhaust$$1() {
  10135. return exhaust$1()(this);
  10136. }
  10137. Observable.prototype.exhaust = exhaust$$1;
  10138. /* tslint:enable:max-line-length */
  10139. /**
  10140. * Projects each source value to an Observable which is merged in the output
  10141. * Observable only if the previous projected Observable has completed.
  10142. *
  10143. * <span class="informal">Maps each value to an Observable, then flattens all of
  10144. * these inner Observables using {@link exhaust}.</span>
  10145. *
  10146. * <img src="./img/exhaustMap.png" width="100%">
  10147. *
  10148. * Returns an Observable that emits items based on applying a function that you
  10149. * supply to each item emitted by the source Observable, where that function
  10150. * returns an (so-called "inner") Observable. When it projects a source value to
  10151. * an Observable, the output Observable begins emitting the items emitted by
  10152. * that projected Observable. However, `exhaustMap` ignores every new projected
  10153. * Observable if the previous projected Observable has not yet completed. Once
  10154. * that one completes, it will accept and flatten the next projected Observable
  10155. * and repeat this process.
  10156. *
  10157. * @example <caption>Run a finite timer for each click, only if there is no currently active timer</caption>
  10158. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10159. * var result = clicks.exhaustMap((ev) => Rx.Observable.interval(1000).take(5));
  10160. * result.subscribe(x => console.log(x));
  10161. *
  10162. * @see {@link concatMap}
  10163. * @see {@link exhaust}
  10164. * @see {@link mergeMap}
  10165. * @see {@link switchMap}
  10166. *
  10167. * @param {function(value: T, ?index: number): ObservableInput} project A function
  10168. * that, when applied to an item emitted by the source Observable, returns an
  10169. * Observable.
  10170. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  10171. * A function to produce the value on the output Observable based on the values
  10172. * and the indices of the source (outer) emission and the inner Observable
  10173. * emission. The arguments passed to this function are:
  10174. * - `outerValue`: the value that came from the source
  10175. * - `innerValue`: the value that came from the projected Observable
  10176. * - `outerIndex`: the "index" of the value that came from the source
  10177. * - `innerIndex`: the "index" of the value from the projected Observable
  10178. * @return {Observable} An Observable containing projected Observables
  10179. * of each item of the source, ignoring projected Observables that start before
  10180. * their preceding Observable has completed.
  10181. * @method exhaustMap
  10182. * @owner Observable
  10183. */
  10184. function exhaustMap$1(project, resultSelector) {
  10185. return function (source) { return source.lift(new SwitchFirstMapOperator(project, resultSelector)); };
  10186. }
  10187. var SwitchFirstMapOperator = (function () {
  10188. function SwitchFirstMapOperator(project, resultSelector) {
  10189. this.project = project;
  10190. this.resultSelector = resultSelector;
  10191. }
  10192. SwitchFirstMapOperator.prototype.call = function (subscriber, source) {
  10193. return source.subscribe(new SwitchFirstMapSubscriber(subscriber, this.project, this.resultSelector));
  10194. };
  10195. return SwitchFirstMapOperator;
  10196. }());
  10197. /**
  10198. * We need this JSDoc comment for affecting ESDoc.
  10199. * @ignore
  10200. * @extends {Ignored}
  10201. */
  10202. var SwitchFirstMapSubscriber = (function (_super) {
  10203. __extends(SwitchFirstMapSubscriber, _super);
  10204. function SwitchFirstMapSubscriber(destination, project, resultSelector) {
  10205. _super.call(this, destination);
  10206. this.project = project;
  10207. this.resultSelector = resultSelector;
  10208. this.hasSubscription = false;
  10209. this.hasCompleted = false;
  10210. this.index = 0;
  10211. }
  10212. SwitchFirstMapSubscriber.prototype._next = function (value) {
  10213. if (!this.hasSubscription) {
  10214. this.tryNext(value);
  10215. }
  10216. };
  10217. SwitchFirstMapSubscriber.prototype.tryNext = function (value) {
  10218. var index = this.index++;
  10219. var destination = this.destination;
  10220. try {
  10221. var result = this.project(value, index);
  10222. this.hasSubscription = true;
  10223. this.add(subscribeToResult(this, result, value, index));
  10224. }
  10225. catch (err) {
  10226. destination.error(err);
  10227. }
  10228. };
  10229. SwitchFirstMapSubscriber.prototype._complete = function () {
  10230. this.hasCompleted = true;
  10231. if (!this.hasSubscription) {
  10232. this.destination.complete();
  10233. }
  10234. };
  10235. SwitchFirstMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  10236. var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
  10237. if (resultSelector) {
  10238. this.trySelectResult(outerValue, innerValue, outerIndex, innerIndex);
  10239. }
  10240. else {
  10241. destination.next(innerValue);
  10242. }
  10243. };
  10244. SwitchFirstMapSubscriber.prototype.trySelectResult = function (outerValue, innerValue, outerIndex, innerIndex) {
  10245. var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
  10246. try {
  10247. var result = resultSelector(outerValue, innerValue, outerIndex, innerIndex);
  10248. destination.next(result);
  10249. }
  10250. catch (err) {
  10251. destination.error(err);
  10252. }
  10253. };
  10254. SwitchFirstMapSubscriber.prototype.notifyError = function (err) {
  10255. this.destination.error(err);
  10256. };
  10257. SwitchFirstMapSubscriber.prototype.notifyComplete = function (innerSub) {
  10258. this.remove(innerSub);
  10259. this.hasSubscription = false;
  10260. if (this.hasCompleted) {
  10261. this.destination.complete();
  10262. }
  10263. };
  10264. return SwitchFirstMapSubscriber;
  10265. }(OuterSubscriber));
  10266. /* tslint:enable:max-line-length */
  10267. /**
  10268. * Projects each source value to an Observable which is merged in the output
  10269. * Observable only if the previous projected Observable has completed.
  10270. *
  10271. * <span class="informal">Maps each value to an Observable, then flattens all of
  10272. * these inner Observables using {@link exhaust}.</span>
  10273. *
  10274. * <img src="./img/exhaustMap.png" width="100%">
  10275. *
  10276. * Returns an Observable that emits items based on applying a function that you
  10277. * supply to each item emitted by the source Observable, where that function
  10278. * returns an (so-called "inner") Observable. When it projects a source value to
  10279. * an Observable, the output Observable begins emitting the items emitted by
  10280. * that projected Observable. However, `exhaustMap` ignores every new projected
  10281. * Observable if the previous projected Observable has not yet completed. Once
  10282. * that one completes, it will accept and flatten the next projected Observable
  10283. * and repeat this process.
  10284. *
  10285. * @example <caption>Run a finite timer for each click, only if there is no currently active timer</caption>
  10286. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10287. * var result = clicks.exhaustMap((ev) => Rx.Observable.interval(1000).take(5));
  10288. * result.subscribe(x => console.log(x));
  10289. *
  10290. * @see {@link concatMap}
  10291. * @see {@link exhaust}
  10292. * @see {@link mergeMap}
  10293. * @see {@link switchMap}
  10294. *
  10295. * @param {function(value: T, ?index: number): ObservableInput} project A function
  10296. * that, when applied to an item emitted by the source Observable, returns an
  10297. * Observable.
  10298. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  10299. * A function to produce the value on the output Observable based on the values
  10300. * and the indices of the source (outer) emission and the inner Observable
  10301. * emission. The arguments passed to this function are:
  10302. * - `outerValue`: the value that came from the source
  10303. * - `innerValue`: the value that came from the projected Observable
  10304. * - `outerIndex`: the "index" of the value that came from the source
  10305. * - `innerIndex`: the "index" of the value from the projected Observable
  10306. * @return {Observable} An Observable containing projected Observables
  10307. * of each item of the source, ignoring projected Observables that start before
  10308. * their preceding Observable has completed.
  10309. * @method exhaustMap
  10310. * @owner Observable
  10311. */
  10312. function exhaustMap$$1(project, resultSelector) {
  10313. return exhaustMap$1(project, resultSelector)(this);
  10314. }
  10315. Observable.prototype.exhaustMap = exhaustMap$$1;
  10316. /* tslint:enable:max-line-length */
  10317. /**
  10318. * Recursively projects each source value to an Observable which is merged in
  10319. * the output Observable.
  10320. *
  10321. * <span class="informal">It's similar to {@link mergeMap}, but applies the
  10322. * projection function to every source value as well as every output value.
  10323. * It's recursive.</span>
  10324. *
  10325. * <img src="./img/expand.png" width="100%">
  10326. *
  10327. * Returns an Observable that emits items based on applying a function that you
  10328. * supply to each item emitted by the source Observable, where that function
  10329. * returns an Observable, and then merging those resulting Observables and
  10330. * emitting the results of this merger. *Expand* will re-emit on the output
  10331. * Observable every source value. Then, each output value is given to the
  10332. * `project` function which returns an inner Observable to be merged on the
  10333. * output Observable. Those output values resulting from the projection are also
  10334. * given to the `project` function to produce new output values. This is how
  10335. * *expand* behaves recursively.
  10336. *
  10337. * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
  10338. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10339. * var powersOfTwo = clicks
  10340. * .mapTo(1)
  10341. * .expand(x => Rx.Observable.of(2 * x).delay(1000))
  10342. * .take(10);
  10343. * powersOfTwo.subscribe(x => console.log(x));
  10344. *
  10345. * @see {@link mergeMap}
  10346. * @see {@link mergeScan}
  10347. *
  10348. * @param {function(value: T, index: number) => Observable} project A function
  10349. * that, when applied to an item emitted by the source or the output Observable,
  10350. * returns an Observable.
  10351. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  10352. * Observables being subscribed to concurrently.
  10353. * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
  10354. * each projected inner Observable.
  10355. * @return {Observable} An Observable that emits the source values and also
  10356. * result of applying the projection function to each value emitted on the
  10357. * output Observable and and merging the results of the Observables obtained
  10358. * from this transformation.
  10359. * @method expand
  10360. * @owner Observable
  10361. */
  10362. function expand$1(project, concurrent, scheduler) {
  10363. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  10364. if (scheduler === void 0) { scheduler = undefined; }
  10365. concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
  10366. return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
  10367. }
  10368. var ExpandOperator = (function () {
  10369. function ExpandOperator(project, concurrent, scheduler) {
  10370. this.project = project;
  10371. this.concurrent = concurrent;
  10372. this.scheduler = scheduler;
  10373. }
  10374. ExpandOperator.prototype.call = function (subscriber, source) {
  10375. return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
  10376. };
  10377. return ExpandOperator;
  10378. }());
  10379. /**
  10380. * We need this JSDoc comment for affecting ESDoc.
  10381. * @ignore
  10382. * @extends {Ignored}
  10383. */
  10384. var ExpandSubscriber = (function (_super) {
  10385. __extends(ExpandSubscriber, _super);
  10386. function ExpandSubscriber(destination, project, concurrent, scheduler) {
  10387. _super.call(this, destination);
  10388. this.project = project;
  10389. this.concurrent = concurrent;
  10390. this.scheduler = scheduler;
  10391. this.index = 0;
  10392. this.active = 0;
  10393. this.hasCompleted = false;
  10394. if (concurrent < Number.POSITIVE_INFINITY) {
  10395. this.buffer = [];
  10396. }
  10397. }
  10398. ExpandSubscriber.dispatch = function (arg) {
  10399. var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
  10400. subscriber.subscribeToProjection(result, value, index);
  10401. };
  10402. ExpandSubscriber.prototype._next = function (value) {
  10403. var destination = this.destination;
  10404. if (destination.closed) {
  10405. this._complete();
  10406. return;
  10407. }
  10408. var index = this.index++;
  10409. if (this.active < this.concurrent) {
  10410. destination.next(value);
  10411. var result = tryCatch(this.project)(value, index);
  10412. if (result === errorObject) {
  10413. destination.error(errorObject.e);
  10414. }
  10415. else if (!this.scheduler) {
  10416. this.subscribeToProjection(result, value, index);
  10417. }
  10418. else {
  10419. var state = { subscriber: this, result: result, value: value, index: index };
  10420. this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
  10421. }
  10422. }
  10423. else {
  10424. this.buffer.push(value);
  10425. }
  10426. };
  10427. ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
  10428. this.active++;
  10429. this.add(subscribeToResult(this, result, value, index));
  10430. };
  10431. ExpandSubscriber.prototype._complete = function () {
  10432. this.hasCompleted = true;
  10433. if (this.hasCompleted && this.active === 0) {
  10434. this.destination.complete();
  10435. }
  10436. };
  10437. ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  10438. this._next(innerValue);
  10439. };
  10440. ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
  10441. var buffer = this.buffer;
  10442. this.remove(innerSub);
  10443. this.active--;
  10444. if (buffer && buffer.length > 0) {
  10445. this._next(buffer.shift());
  10446. }
  10447. if (this.hasCompleted && this.active === 0) {
  10448. this.destination.complete();
  10449. }
  10450. };
  10451. return ExpandSubscriber;
  10452. }(OuterSubscriber));
  10453. /* tslint:enable:max-line-length */
  10454. /**
  10455. * Recursively projects each source value to an Observable which is merged in
  10456. * the output Observable.
  10457. *
  10458. * <span class="informal">It's similar to {@link mergeMap}, but applies the
  10459. * projection function to every source value as well as every output value.
  10460. * It's recursive.</span>
  10461. *
  10462. * <img src="./img/expand.png" width="100%">
  10463. *
  10464. * Returns an Observable that emits items based on applying a function that you
  10465. * supply to each item emitted by the source Observable, where that function
  10466. * returns an Observable, and then merging those resulting Observables and
  10467. * emitting the results of this merger. *Expand* will re-emit on the output
  10468. * Observable every source value. Then, each output value is given to the
  10469. * `project` function which returns an inner Observable to be merged on the
  10470. * output Observable. Those output values resulting from the projection are also
  10471. * given to the `project` function to produce new output values. This is how
  10472. * *expand* behaves recursively.
  10473. *
  10474. * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
  10475. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10476. * var powersOfTwo = clicks
  10477. * .mapTo(1)
  10478. * .expand(x => Rx.Observable.of(2 * x).delay(1000))
  10479. * .take(10);
  10480. * powersOfTwo.subscribe(x => console.log(x));
  10481. *
  10482. * @see {@link mergeMap}
  10483. * @see {@link mergeScan}
  10484. *
  10485. * @param {function(value: T, index: number) => Observable} project A function
  10486. * that, when applied to an item emitted by the source or the output Observable,
  10487. * returns an Observable.
  10488. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  10489. * Observables being subscribed to concurrently.
  10490. * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
  10491. * each projected inner Observable.
  10492. * @return {Observable} An Observable that emits the source values and also
  10493. * result of applying the projection function to each value emitted on the
  10494. * output Observable and and merging the results of the Observables obtained
  10495. * from this transformation.
  10496. * @method expand
  10497. * @owner Observable
  10498. */
  10499. function expand$$1(project, concurrent, scheduler) {
  10500. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  10501. if (scheduler === void 0) { scheduler = undefined; }
  10502. concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
  10503. return expand$1(project, concurrent, scheduler)(this);
  10504. }
  10505. Observable.prototype.expand = expand$$1;
  10506. /**
  10507. * An error thrown when an element was queried at a certain index of an
  10508. * Observable, but no such index or position exists in that sequence.
  10509. *
  10510. * @see {@link elementAt}
  10511. * @see {@link take}
  10512. * @see {@link takeLast}
  10513. *
  10514. * @class ArgumentOutOfRangeError
  10515. */
  10516. var ArgumentOutOfRangeError = (function (_super) {
  10517. __extends(ArgumentOutOfRangeError, _super);
  10518. function ArgumentOutOfRangeError() {
  10519. var err = _super.call(this, 'argument out of range');
  10520. this.name = err.name = 'ArgumentOutOfRangeError';
  10521. this.stack = err.stack;
  10522. this.message = err.message;
  10523. }
  10524. return ArgumentOutOfRangeError;
  10525. }(Error));
  10526. /**
  10527. * Emits the single value at the specified `index` in a sequence of emissions
  10528. * from the source Observable.
  10529. *
  10530. * <span class="informal">Emits only the i-th value, then completes.</span>
  10531. *
  10532. * <img src="./img/elementAt.png" width="100%">
  10533. *
  10534. * `elementAt` returns an Observable that emits the item at the specified
  10535. * `index` in the source Observable, or a default value if that `index` is out
  10536. * of range and the `default` argument is provided. If the `default` argument is
  10537. * not given and the `index` is out of range, the output Observable will emit an
  10538. * `ArgumentOutOfRangeError` error.
  10539. *
  10540. * @example <caption>Emit only the third click event</caption>
  10541. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10542. * var result = clicks.elementAt(2);
  10543. * result.subscribe(x => console.log(x));
  10544. *
  10545. * // Results in:
  10546. * // click 1 = nothing
  10547. * // click 2 = nothing
  10548. * // click 3 = MouseEvent object logged to console
  10549. *
  10550. * @see {@link first}
  10551. * @see {@link last}
  10552. * @see {@link skip}
  10553. * @see {@link single}
  10554. * @see {@link take}
  10555. *
  10556. * @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an
  10557. * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0` or the
  10558. * Observable has completed before emitting the i-th `next` notification.
  10559. *
  10560. * @param {number} index Is the number `i` for the i-th source emission that has
  10561. * happened since the subscription, starting from the number `0`.
  10562. * @param {T} [defaultValue] The default value returned for missing indices.
  10563. * @return {Observable} An Observable that emits a single item, if it is found.
  10564. * Otherwise, will emit the default value if given. If not, then emits an error.
  10565. * @method elementAt
  10566. * @owner Observable
  10567. */
  10568. function elementAt$1(index, defaultValue) {
  10569. return function (source) { return source.lift(new ElementAtOperator(index, defaultValue)); };
  10570. }
  10571. var ElementAtOperator = (function () {
  10572. function ElementAtOperator(index, defaultValue) {
  10573. this.index = index;
  10574. this.defaultValue = defaultValue;
  10575. if (index < 0) {
  10576. throw new ArgumentOutOfRangeError;
  10577. }
  10578. }
  10579. ElementAtOperator.prototype.call = function (subscriber, source) {
  10580. return source.subscribe(new ElementAtSubscriber(subscriber, this.index, this.defaultValue));
  10581. };
  10582. return ElementAtOperator;
  10583. }());
  10584. /**
  10585. * We need this JSDoc comment for affecting ESDoc.
  10586. * @ignore
  10587. * @extends {Ignored}
  10588. */
  10589. var ElementAtSubscriber = (function (_super) {
  10590. __extends(ElementAtSubscriber, _super);
  10591. function ElementAtSubscriber(destination, index, defaultValue) {
  10592. _super.call(this, destination);
  10593. this.index = index;
  10594. this.defaultValue = defaultValue;
  10595. }
  10596. ElementAtSubscriber.prototype._next = function (x) {
  10597. if (this.index-- === 0) {
  10598. this.destination.next(x);
  10599. this.destination.complete();
  10600. }
  10601. };
  10602. ElementAtSubscriber.prototype._complete = function () {
  10603. var destination = this.destination;
  10604. if (this.index >= 0) {
  10605. if (typeof this.defaultValue !== 'undefined') {
  10606. destination.next(this.defaultValue);
  10607. }
  10608. else {
  10609. destination.error(new ArgumentOutOfRangeError);
  10610. }
  10611. }
  10612. destination.complete();
  10613. };
  10614. return ElementAtSubscriber;
  10615. }(Subscriber));
  10616. /**
  10617. * Emits the single value at the specified `index` in a sequence of emissions
  10618. * from the source Observable.
  10619. *
  10620. * <span class="informal">Emits only the i-th value, then completes.</span>
  10621. *
  10622. * <img src="./img/elementAt.png" width="100%">
  10623. *
  10624. * `elementAt` returns an Observable that emits the item at the specified
  10625. * `index` in the source Observable, or a default value if that `index` is out
  10626. * of range and the `default` argument is provided. If the `default` argument is
  10627. * not given and the `index` is out of range, the output Observable will emit an
  10628. * `ArgumentOutOfRangeError` error.
  10629. *
  10630. * @example <caption>Emit only the third click event</caption>
  10631. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10632. * var result = clicks.elementAt(2);
  10633. * result.subscribe(x => console.log(x));
  10634. *
  10635. * // Results in:
  10636. * // click 1 = nothing
  10637. * // click 2 = nothing
  10638. * // click 3 = MouseEvent object logged to console
  10639. *
  10640. * @see {@link first}
  10641. * @see {@link last}
  10642. * @see {@link skip}
  10643. * @see {@link single}
  10644. * @see {@link take}
  10645. *
  10646. * @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an
  10647. * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0` or the
  10648. * Observable has completed before emitting the i-th `next` notification.
  10649. *
  10650. * @param {number} index Is the number `i` for the i-th source emission that has
  10651. * happened since the subscription, starting from the number `0`.
  10652. * @param {T} [defaultValue] The default value returned for missing indices.
  10653. * @return {Observable} An Observable that emits a single item, if it is found.
  10654. * Otherwise, will emit the default value if given. If not, then emits an error.
  10655. * @method elementAt
  10656. * @owner Observable
  10657. */
  10658. function elementAt$$1(index, defaultValue) {
  10659. return elementAt$1(index, defaultValue)(this);
  10660. }
  10661. Observable.prototype.elementAt = elementAt$$1;
  10662. /* tslint:enable:max-line-length */
  10663. /**
  10664. * Filter items emitted by the source Observable by only emitting those that
  10665. * satisfy a specified predicate.
  10666. *
  10667. * <span class="informal">Like
  10668. * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
  10669. * it only emits a value from the source if it passes a criterion function.</span>
  10670. *
  10671. * <img src="./img/filter.png" width="100%">
  10672. *
  10673. * Similar to the well-known `Array.prototype.filter` method, this operator
  10674. * takes values from the source Observable, passes them through a `predicate`
  10675. * function and only emits those values that yielded `true`.
  10676. *
  10677. * @example <caption>Emit only click events whose target was a DIV element</caption>
  10678. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10679. * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
  10680. * clicksOnDivs.subscribe(x => console.log(x));
  10681. *
  10682. * @see {@link distinct}
  10683. * @see {@link distinctUntilChanged}
  10684. * @see {@link distinctUntilKeyChanged}
  10685. * @see {@link ignoreElements}
  10686. * @see {@link partition}
  10687. * @see {@link skip}
  10688. *
  10689. * @param {function(value: T, index: number): boolean} predicate A function that
  10690. * evaluates each value emitted by the source Observable. If it returns `true`,
  10691. * the value is emitted, if `false` the value is not passed to the output
  10692. * Observable. The `index` parameter is the number `i` for the i-th source
  10693. * emission that has happened since the subscription, starting from the number
  10694. * `0`.
  10695. * @param {any} [thisArg] An optional argument to determine the value of `this`
  10696. * in the `predicate` function.
  10697. * @return {Observable} An Observable of values from the source that were
  10698. * allowed by the `predicate` function.
  10699. * @method filter
  10700. * @owner Observable
  10701. */
  10702. function filter$1(predicate, thisArg) {
  10703. return function filterOperatorFunction(source) {
  10704. return source.lift(new FilterOperator(predicate, thisArg));
  10705. };
  10706. }
  10707. var FilterOperator = (function () {
  10708. function FilterOperator(predicate, thisArg) {
  10709. this.predicate = predicate;
  10710. this.thisArg = thisArg;
  10711. }
  10712. FilterOperator.prototype.call = function (subscriber, source) {
  10713. return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
  10714. };
  10715. return FilterOperator;
  10716. }());
  10717. /**
  10718. * We need this JSDoc comment for affecting ESDoc.
  10719. * @ignore
  10720. * @extends {Ignored}
  10721. */
  10722. var FilterSubscriber = (function (_super) {
  10723. __extends(FilterSubscriber, _super);
  10724. function FilterSubscriber(destination, predicate, thisArg) {
  10725. _super.call(this, destination);
  10726. this.predicate = predicate;
  10727. this.thisArg = thisArg;
  10728. this.count = 0;
  10729. }
  10730. // the try catch block below is left specifically for
  10731. // optimization and perf reasons. a tryCatcher is not necessary here.
  10732. FilterSubscriber.prototype._next = function (value) {
  10733. var result;
  10734. try {
  10735. result = this.predicate.call(this.thisArg, value, this.count++);
  10736. }
  10737. catch (err) {
  10738. this.destination.error(err);
  10739. return;
  10740. }
  10741. if (result) {
  10742. this.destination.next(value);
  10743. }
  10744. };
  10745. return FilterSubscriber;
  10746. }(Subscriber));
  10747. /* tslint:enable:max-line-length */
  10748. /**
  10749. * Filter items emitted by the source Observable by only emitting those that
  10750. * satisfy a specified predicate.
  10751. *
  10752. * <span class="informal">Like
  10753. * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
  10754. * it only emits a value from the source if it passes a criterion function.</span>
  10755. *
  10756. * <img src="./img/filter.png" width="100%">
  10757. *
  10758. * Similar to the well-known `Array.prototype.filter` method, this operator
  10759. * takes values from the source Observable, passes them through a `predicate`
  10760. * function and only emits those values that yielded `true`.
  10761. *
  10762. * @example <caption>Emit only click events whose target was a DIV element</caption>
  10763. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10764. * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
  10765. * clicksOnDivs.subscribe(x => console.log(x));
  10766. *
  10767. * @see {@link distinct}
  10768. * @see {@link distinctUntilChanged}
  10769. * @see {@link distinctUntilKeyChanged}
  10770. * @see {@link ignoreElements}
  10771. * @see {@link partition}
  10772. * @see {@link skip}
  10773. *
  10774. * @param {function(value: T, index: number): boolean} predicate A function that
  10775. * evaluates each value emitted by the source Observable. If it returns `true`,
  10776. * the value is emitted, if `false` the value is not passed to the output
  10777. * Observable. The `index` parameter is the number `i` for the i-th source
  10778. * emission that has happened since the subscription, starting from the number
  10779. * `0`.
  10780. * @param {any} [thisArg] An optional argument to determine the value of `this`
  10781. * in the `predicate` function.
  10782. * @return {Observable} An Observable of values from the source that were
  10783. * allowed by the `predicate` function.
  10784. * @method filter
  10785. * @owner Observable
  10786. */
  10787. function filter$$1(predicate, thisArg) {
  10788. return filter$1(predicate, thisArg)(this);
  10789. }
  10790. Observable.prototype.filter = filter$$1;
  10791. /**
  10792. * Returns an Observable that mirrors the source Observable, but will call a specified function when
  10793. * the source terminates on complete or error.
  10794. * @param {function} callback Function to be called when source terminates.
  10795. * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
  10796. * @method finally
  10797. * @owner Observable
  10798. */
  10799. function finalize(callback) {
  10800. return function (source) { return source.lift(new FinallyOperator(callback)); };
  10801. }
  10802. var FinallyOperator = (function () {
  10803. function FinallyOperator(callback) {
  10804. this.callback = callback;
  10805. }
  10806. FinallyOperator.prototype.call = function (subscriber, source) {
  10807. return source.subscribe(new FinallySubscriber(subscriber, this.callback));
  10808. };
  10809. return FinallyOperator;
  10810. }());
  10811. /**
  10812. * We need this JSDoc comment for affecting ESDoc.
  10813. * @ignore
  10814. * @extends {Ignored}
  10815. */
  10816. var FinallySubscriber = (function (_super) {
  10817. __extends(FinallySubscriber, _super);
  10818. function FinallySubscriber(destination, callback) {
  10819. _super.call(this, destination);
  10820. this.add(new Subscription(callback));
  10821. }
  10822. return FinallySubscriber;
  10823. }(Subscriber));
  10824. /**
  10825. * Returns an Observable that mirrors the source Observable, but will call a specified function when
  10826. * the source terminates on complete or error.
  10827. * @param {function} callback Function to be called when source terminates.
  10828. * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
  10829. * @method finally
  10830. * @owner Observable
  10831. */
  10832. function _finally(callback) {
  10833. return finalize(callback)(this);
  10834. }
  10835. Observable.prototype.finally = _finally;
  10836. Observable.prototype._finally = _finally;
  10837. /**
  10838. * Emits only the first value emitted by the source Observable that meets some
  10839. * condition.
  10840. *
  10841. * <span class="informal">Finds the first value that passes some test and emits
  10842. * that.</span>
  10843. *
  10844. * <img src="./img/find.png" width="100%">
  10845. *
  10846. * `find` searches for the first item in the source Observable that matches the
  10847. * specified condition embodied by the `predicate`, and returns the first
  10848. * occurrence in the source. Unlike {@link first}, the `predicate` is required
  10849. * in `find`, and does not emit an error if a valid value is not found.
  10850. *
  10851. * @example <caption>Find and emit the first click that happens on a DIV element</caption>
  10852. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10853. * var result = clicks.find(ev => ev.target.tagName === 'DIV');
  10854. * result.subscribe(x => console.log(x));
  10855. *
  10856. * @see {@link filter}
  10857. * @see {@link first}
  10858. * @see {@link findIndex}
  10859. * @see {@link take}
  10860. *
  10861. * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
  10862. * A function called with each item to test for condition matching.
  10863. * @param {any} [thisArg] An optional argument to determine the value of `this`
  10864. * in the `predicate` function.
  10865. * @return {Observable<T>} An Observable of the first item that matches the
  10866. * condition.
  10867. * @method find
  10868. * @owner Observable
  10869. */
  10870. function find$1(predicate, thisArg) {
  10871. if (typeof predicate !== 'function') {
  10872. throw new TypeError('predicate is not a function');
  10873. }
  10874. return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); };
  10875. }
  10876. var FindValueOperator = (function () {
  10877. function FindValueOperator(predicate, source, yieldIndex, thisArg) {
  10878. this.predicate = predicate;
  10879. this.source = source;
  10880. this.yieldIndex = yieldIndex;
  10881. this.thisArg = thisArg;
  10882. }
  10883. FindValueOperator.prototype.call = function (observer, source) {
  10884. return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
  10885. };
  10886. return FindValueOperator;
  10887. }());
  10888. /**
  10889. * We need this JSDoc comment for affecting ESDoc.
  10890. * @ignore
  10891. * @extends {Ignored}
  10892. */
  10893. var FindValueSubscriber = (function (_super) {
  10894. __extends(FindValueSubscriber, _super);
  10895. function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) {
  10896. _super.call(this, destination);
  10897. this.predicate = predicate;
  10898. this.source = source;
  10899. this.yieldIndex = yieldIndex;
  10900. this.thisArg = thisArg;
  10901. this.index = 0;
  10902. }
  10903. FindValueSubscriber.prototype.notifyComplete = function (value) {
  10904. var destination = this.destination;
  10905. destination.next(value);
  10906. destination.complete();
  10907. };
  10908. FindValueSubscriber.prototype._next = function (value) {
  10909. var _a = this, predicate = _a.predicate, thisArg = _a.thisArg;
  10910. var index = this.index++;
  10911. try {
  10912. var result = predicate.call(thisArg || this, value, index, this.source);
  10913. if (result) {
  10914. this.notifyComplete(this.yieldIndex ? index : value);
  10915. }
  10916. }
  10917. catch (err) {
  10918. this.destination.error(err);
  10919. }
  10920. };
  10921. FindValueSubscriber.prototype._complete = function () {
  10922. this.notifyComplete(this.yieldIndex ? -1 : undefined);
  10923. };
  10924. return FindValueSubscriber;
  10925. }(Subscriber));
  10926. /* tslint:enable:max-line-length */
  10927. /**
  10928. * Emits only the first value emitted by the source Observable that meets some
  10929. * condition.
  10930. *
  10931. * <span class="informal">Finds the first value that passes some test and emits
  10932. * that.</span>
  10933. *
  10934. * <img src="./img/find.png" width="100%">
  10935. *
  10936. * `find` searches for the first item in the source Observable that matches the
  10937. * specified condition embodied by the `predicate`, and returns the first
  10938. * occurrence in the source. Unlike {@link first}, the `predicate` is required
  10939. * in `find`, and does not emit an error if a valid value is not found.
  10940. *
  10941. * @example <caption>Find and emit the first click that happens on a DIV element</caption>
  10942. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10943. * var result = clicks.find(ev => ev.target.tagName === 'DIV');
  10944. * result.subscribe(x => console.log(x));
  10945. *
  10946. * @see {@link filter}
  10947. * @see {@link first}
  10948. * @see {@link findIndex}
  10949. * @see {@link take}
  10950. *
  10951. * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
  10952. * A function called with each item to test for condition matching.
  10953. * @param {any} [thisArg] An optional argument to determine the value of `this`
  10954. * in the `predicate` function.
  10955. * @return {Observable<T>} An Observable of the first item that matches the
  10956. * condition.
  10957. * @method find
  10958. * @owner Observable
  10959. */
  10960. function find$$1(predicate, thisArg) {
  10961. return find$1(predicate, thisArg)(this);
  10962. }
  10963. Observable.prototype.find = find$$1;
  10964. /**
  10965. * Emits only the index of the first value emitted by the source Observable that
  10966. * meets some condition.
  10967. *
  10968. * <span class="informal">It's like {@link find}, but emits the index of the
  10969. * found value, not the value itself.</span>
  10970. *
  10971. * <img src="./img/findIndex.png" width="100%">
  10972. *
  10973. * `findIndex` searches for the first item in the source Observable that matches
  10974. * the specified condition embodied by the `predicate`, and returns the
  10975. * (zero-based) index of the first occurrence in the source. Unlike
  10976. * {@link first}, the `predicate` is required in `findIndex`, and does not emit
  10977. * an error if a valid value is not found.
  10978. *
  10979. * @example <caption>Emit the index of first click that happens on a DIV element</caption>
  10980. * var clicks = Rx.Observable.fromEvent(document, 'click');
  10981. * var result = clicks.findIndex(ev => ev.target.tagName === 'DIV');
  10982. * result.subscribe(x => console.log(x));
  10983. *
  10984. * @see {@link filter}
  10985. * @see {@link find}
  10986. * @see {@link first}
  10987. * @see {@link take}
  10988. *
  10989. * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
  10990. * A function called with each item to test for condition matching.
  10991. * @param {any} [thisArg] An optional argument to determine the value of `this`
  10992. * in the `predicate` function.
  10993. * @return {Observable} An Observable of the index of the first item that
  10994. * matches the condition.
  10995. * @method find
  10996. * @owner Observable
  10997. */
  10998. function findIndex$1(predicate, thisArg) {
  10999. return function (source) { return source.lift(new FindValueOperator(predicate, source, true, thisArg)); };
  11000. }
  11001. /**
  11002. * Emits only the index of the first value emitted by the source Observable that
  11003. * meets some condition.
  11004. *
  11005. * <span class="informal">It's like {@link find}, but emits the index of the
  11006. * found value, not the value itself.</span>
  11007. *
  11008. * <img src="./img/findIndex.png" width="100%">
  11009. *
  11010. * `findIndex` searches for the first item in the source Observable that matches
  11011. * the specified condition embodied by the `predicate`, and returns the
  11012. * (zero-based) index of the first occurrence in the source. Unlike
  11013. * {@link first}, the `predicate` is required in `findIndex`, and does not emit
  11014. * an error if a valid value is not found.
  11015. *
  11016. * @example <caption>Emit the index of first click that happens on a DIV element</caption>
  11017. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11018. * var result = clicks.findIndex(ev => ev.target.tagName === 'DIV');
  11019. * result.subscribe(x => console.log(x));
  11020. *
  11021. * @see {@link filter}
  11022. * @see {@link find}
  11023. * @see {@link first}
  11024. * @see {@link take}
  11025. *
  11026. * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
  11027. * A function called with each item to test for condition matching.
  11028. * @param {any} [thisArg] An optional argument to determine the value of `this`
  11029. * in the `predicate` function.
  11030. * @return {Observable} An Observable of the index of the first item that
  11031. * matches the condition.
  11032. * @method find
  11033. * @owner Observable
  11034. */
  11035. function findIndex$$1(predicate, thisArg) {
  11036. return findIndex$1(predicate, thisArg)(this);
  11037. }
  11038. Observable.prototype.findIndex = findIndex$$1;
  11039. /**
  11040. * An error thrown when an Observable or a sequence was queried but has no
  11041. * elements.
  11042. *
  11043. * @see {@link first}
  11044. * @see {@link last}
  11045. * @see {@link single}
  11046. *
  11047. * @class EmptyError
  11048. */
  11049. var EmptyError = (function (_super) {
  11050. __extends(EmptyError, _super);
  11051. function EmptyError() {
  11052. var err = _super.call(this, 'no elements in sequence');
  11053. this.name = err.name = 'EmptyError';
  11054. this.stack = err.stack;
  11055. this.message = err.message;
  11056. }
  11057. return EmptyError;
  11058. }(Error));
  11059. /**
  11060. * Emits only the first value (or the first value that meets some condition)
  11061. * emitted by the source Observable.
  11062. *
  11063. * <span class="informal">Emits only the first value. Or emits only the first
  11064. * value that passes some test.</span>
  11065. *
  11066. * <img src="./img/first.png" width="100%">
  11067. *
  11068. * If called with no arguments, `first` emits the first value of the source
  11069. * Observable, then completes. If called with a `predicate` function, `first`
  11070. * emits the first value of the source that matches the specified condition. It
  11071. * may also take a `resultSelector` function to produce the output value from
  11072. * the input value, and a `defaultValue` to emit in case the source completes
  11073. * before it is able to emit a valid value. Throws an error if `defaultValue`
  11074. * was not provided and a matching element is not found.
  11075. *
  11076. * @example <caption>Emit only the first click that happens on the DOM</caption>
  11077. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11078. * var result = clicks.first();
  11079. * result.subscribe(x => console.log(x));
  11080. *
  11081. * @example <caption>Emits the first click that happens on a DIV</caption>
  11082. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11083. * var result = clicks.first(ev => ev.target.tagName === 'DIV');
  11084. * result.subscribe(x => console.log(x));
  11085. *
  11086. * @see {@link filter}
  11087. * @see {@link find}
  11088. * @see {@link take}
  11089. *
  11090. * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
  11091. * callback if the Observable completes before any `next` notification was sent.
  11092. *
  11093. * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
  11094. * An optional function called with each item to test for condition matching.
  11095. * @param {function(value: T, index: number): R} [resultSelector] A function to
  11096. * produce the value on the output Observable based on the values
  11097. * and the indices of the source Observable. The arguments passed to this
  11098. * function are:
  11099. * - `value`: the value that was emitted on the source.
  11100. * - `index`: the "index" of the value from the source.
  11101. * @param {R} [defaultValue] The default value emitted in case no valid value
  11102. * was found on the source.
  11103. * @return {Observable<T|R>} An Observable of the first item that matches the
  11104. * condition.
  11105. * @method first
  11106. * @owner Observable
  11107. */
  11108. function first$1(predicate, resultSelector, defaultValue) {
  11109. return function (source) { return source.lift(new FirstOperator(predicate, resultSelector, defaultValue, source)); };
  11110. }
  11111. var FirstOperator = (function () {
  11112. function FirstOperator(predicate, resultSelector, defaultValue, source) {
  11113. this.predicate = predicate;
  11114. this.resultSelector = resultSelector;
  11115. this.defaultValue = defaultValue;
  11116. this.source = source;
  11117. }
  11118. FirstOperator.prototype.call = function (observer, source) {
  11119. return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
  11120. };
  11121. return FirstOperator;
  11122. }());
  11123. /**
  11124. * We need this JSDoc comment for affecting ESDoc.
  11125. * @ignore
  11126. * @extends {Ignored}
  11127. */
  11128. var FirstSubscriber = (function (_super) {
  11129. __extends(FirstSubscriber, _super);
  11130. function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
  11131. _super.call(this, destination);
  11132. this.predicate = predicate;
  11133. this.resultSelector = resultSelector;
  11134. this.defaultValue = defaultValue;
  11135. this.source = source;
  11136. this.index = 0;
  11137. this.hasCompleted = false;
  11138. this._emitted = false;
  11139. }
  11140. FirstSubscriber.prototype._next = function (value) {
  11141. var index = this.index++;
  11142. if (this.predicate) {
  11143. this._tryPredicate(value, index);
  11144. }
  11145. else {
  11146. this._emit(value, index);
  11147. }
  11148. };
  11149. FirstSubscriber.prototype._tryPredicate = function (value, index) {
  11150. var result;
  11151. try {
  11152. result = this.predicate(value, index, this.source);
  11153. }
  11154. catch (err) {
  11155. this.destination.error(err);
  11156. return;
  11157. }
  11158. if (result) {
  11159. this._emit(value, index);
  11160. }
  11161. };
  11162. FirstSubscriber.prototype._emit = function (value, index) {
  11163. if (this.resultSelector) {
  11164. this._tryResultSelector(value, index);
  11165. return;
  11166. }
  11167. this._emitFinal(value);
  11168. };
  11169. FirstSubscriber.prototype._tryResultSelector = function (value, index) {
  11170. var result;
  11171. try {
  11172. result = this.resultSelector(value, index);
  11173. }
  11174. catch (err) {
  11175. this.destination.error(err);
  11176. return;
  11177. }
  11178. this._emitFinal(result);
  11179. };
  11180. FirstSubscriber.prototype._emitFinal = function (value) {
  11181. var destination = this.destination;
  11182. if (!this._emitted) {
  11183. this._emitted = true;
  11184. destination.next(value);
  11185. destination.complete();
  11186. this.hasCompleted = true;
  11187. }
  11188. };
  11189. FirstSubscriber.prototype._complete = function () {
  11190. var destination = this.destination;
  11191. if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
  11192. destination.next(this.defaultValue);
  11193. destination.complete();
  11194. }
  11195. else if (!this.hasCompleted) {
  11196. destination.error(new EmptyError);
  11197. }
  11198. };
  11199. return FirstSubscriber;
  11200. }(Subscriber));
  11201. /**
  11202. * Emits only the first value (or the first value that meets some condition)
  11203. * emitted by the source Observable.
  11204. *
  11205. * <span class="informal">Emits only the first value. Or emits only the first
  11206. * value that passes some test.</span>
  11207. *
  11208. * <img src="./img/first.png" width="100%">
  11209. *
  11210. * If called with no arguments, `first` emits the first value of the source
  11211. * Observable, then completes. If called with a `predicate` function, `first`
  11212. * emits the first value of the source that matches the specified condition. It
  11213. * may also take a `resultSelector` function to produce the output value from
  11214. * the input value, and a `defaultValue` to emit in case the source completes
  11215. * before it is able to emit a valid value. Throws an error if `defaultValue`
  11216. * was not provided and a matching element is not found.
  11217. *
  11218. * @example <caption>Emit only the first click that happens on the DOM</caption>
  11219. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11220. * var result = clicks.first();
  11221. * result.subscribe(x => console.log(x));
  11222. *
  11223. * @example <caption>Emits the first click that happens on a DIV</caption>
  11224. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11225. * var result = clicks.first(ev => ev.target.tagName === 'DIV');
  11226. * result.subscribe(x => console.log(x));
  11227. *
  11228. * @see {@link filter}
  11229. * @see {@link find}
  11230. * @see {@link take}
  11231. *
  11232. * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
  11233. * callback if the Observable completes before any `next` notification was sent.
  11234. *
  11235. * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
  11236. * An optional function called with each item to test for condition matching.
  11237. * @param {function(value: T, index: number): R} [resultSelector] A function to
  11238. * produce the value on the output Observable based on the values
  11239. * and the indices of the source Observable. The arguments passed to this
  11240. * function are:
  11241. * - `value`: the value that was emitted on the source.
  11242. * - `index`: the "index" of the value from the source.
  11243. * @param {R} [defaultValue] The default value emitted in case no valid value
  11244. * was found on the source.
  11245. * @return {Observable<T|R>} An Observable of the first item that matches the
  11246. * condition.
  11247. * @method first
  11248. * @owner Observable
  11249. */
  11250. function first$$1(predicate, resultSelector, defaultValue) {
  11251. return first$1(predicate, resultSelector, defaultValue)(this);
  11252. }
  11253. Observable.prototype.first = first$$1;
  11254. var MapPolyfill = (function () {
  11255. function MapPolyfill() {
  11256. this.size = 0;
  11257. this._values = [];
  11258. this._keys = [];
  11259. }
  11260. MapPolyfill.prototype.get = function (key) {
  11261. var i = this._keys.indexOf(key);
  11262. return i === -1 ? undefined : this._values[i];
  11263. };
  11264. MapPolyfill.prototype.set = function (key, value) {
  11265. var i = this._keys.indexOf(key);
  11266. if (i === -1) {
  11267. this._keys.push(key);
  11268. this._values.push(value);
  11269. this.size++;
  11270. }
  11271. else {
  11272. this._values[i] = value;
  11273. }
  11274. return this;
  11275. };
  11276. MapPolyfill.prototype.delete = function (key) {
  11277. var i = this._keys.indexOf(key);
  11278. if (i === -1) {
  11279. return false;
  11280. }
  11281. this._values.splice(i, 1);
  11282. this._keys.splice(i, 1);
  11283. this.size--;
  11284. return true;
  11285. };
  11286. MapPolyfill.prototype.clear = function () {
  11287. this._keys.length = 0;
  11288. this._values.length = 0;
  11289. this.size = 0;
  11290. };
  11291. MapPolyfill.prototype.forEach = function (cb, thisArg) {
  11292. for (var i = 0; i < this.size; i++) {
  11293. cb.call(thisArg, this._values[i], this._keys[i]);
  11294. }
  11295. };
  11296. return MapPolyfill;
  11297. }());
  11298. var Map = _root.Map || (function () { return MapPolyfill; })();
  11299. var FastMap = (function () {
  11300. function FastMap() {
  11301. this.values = {};
  11302. }
  11303. FastMap.prototype.delete = function (key) {
  11304. this.values[key] = null;
  11305. return true;
  11306. };
  11307. FastMap.prototype.set = function (key, value) {
  11308. this.values[key] = value;
  11309. return this;
  11310. };
  11311. FastMap.prototype.get = function (key) {
  11312. return this.values[key];
  11313. };
  11314. FastMap.prototype.forEach = function (cb, thisArg) {
  11315. var values = this.values;
  11316. for (var key in values) {
  11317. if (values.hasOwnProperty(key) && values[key] !== null) {
  11318. cb.call(thisArg, values[key], key);
  11319. }
  11320. }
  11321. };
  11322. FastMap.prototype.clear = function () {
  11323. this.values = {};
  11324. };
  11325. return FastMap;
  11326. }());
  11327. /* tslint:enable:max-line-length */
  11328. /**
  11329. * Groups the items emitted by an Observable according to a specified criterion,
  11330. * and emits these grouped items as `GroupedObservables`, one
  11331. * {@link GroupedObservable} per group.
  11332. *
  11333. * <img src="./img/groupBy.png" width="100%">
  11334. *
  11335. * @example <caption>Group objects by id and return as array</caption>
  11336. * Observable.of<Obj>({id: 1, name: 'aze1'},
  11337. * {id: 2, name: 'sf2'},
  11338. * {id: 2, name: 'dg2'},
  11339. * {id: 1, name: 'erg1'},
  11340. * {id: 1, name: 'df1'},
  11341. * {id: 2, name: 'sfqfb2'},
  11342. * {id: 3, name: 'qfs3'},
  11343. * {id: 2, name: 'qsgqsfg2'}
  11344. * )
  11345. * .groupBy(p => p.id)
  11346. * .flatMap( (group$) => group$.reduce((acc, cur) => [...acc, cur], []))
  11347. * .subscribe(p => console.log(p));
  11348. *
  11349. * // displays:
  11350. * // [ { id: 1, name: 'aze1' },
  11351. * // { id: 1, name: 'erg1' },
  11352. * // { id: 1, name: 'df1' } ]
  11353. * //
  11354. * // [ { id: 2, name: 'sf2' },
  11355. * // { id: 2, name: 'dg2' },
  11356. * // { id: 2, name: 'sfqfb2' },
  11357. * // { id: 2, name: 'qsgqsfg2' } ]
  11358. * //
  11359. * // [ { id: 3, name: 'qfs3' } ]
  11360. *
  11361. * @example <caption>Pivot data on the id field</caption>
  11362. * Observable.of<Obj>({id: 1, name: 'aze1'},
  11363. * {id: 2, name: 'sf2'},
  11364. * {id: 2, name: 'dg2'},
  11365. * {id: 1, name: 'erg1'},
  11366. * {id: 1, name: 'df1'},
  11367. * {id: 2, name: 'sfqfb2'},
  11368. * {id: 3, name: 'qfs1'},
  11369. * {id: 2, name: 'qsgqsfg2'}
  11370. * )
  11371. * .groupBy(p => p.id, p => p.name)
  11372. * .flatMap( (group$) => group$.reduce((acc, cur) => [...acc, cur], ["" + group$.key]))
  11373. * .map(arr => ({'id': parseInt(arr[0]), 'values': arr.slice(1)}))
  11374. * .subscribe(p => console.log(p));
  11375. *
  11376. * // displays:
  11377. * // { id: 1, values: [ 'aze1', 'erg1', 'df1' ] }
  11378. * // { id: 2, values: [ 'sf2', 'dg2', 'sfqfb2', 'qsgqsfg2' ] }
  11379. * // { id: 3, values: [ 'qfs1' ] }
  11380. *
  11381. * @param {function(value: T): K} keySelector A function that extracts the key
  11382. * for each item.
  11383. * @param {function(value: T): R} [elementSelector] A function that extracts the
  11384. * return element for each item.
  11385. * @param {function(grouped: GroupedObservable<K,R>): Observable<any>} [durationSelector]
  11386. * A function that returns an Observable to determine how long each group should
  11387. * exist.
  11388. * @return {Observable<GroupedObservable<K,R>>} An Observable that emits
  11389. * GroupedObservables, each of which corresponds to a unique key value and each
  11390. * of which emits those items from the source Observable that share that key
  11391. * value.
  11392. * @method groupBy
  11393. * @owner Observable
  11394. */
  11395. function groupBy$1(keySelector, elementSelector, durationSelector, subjectSelector) {
  11396. return function (source) {
  11397. return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
  11398. };
  11399. }
  11400. var GroupByOperator = (function () {
  11401. function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) {
  11402. this.keySelector = keySelector;
  11403. this.elementSelector = elementSelector;
  11404. this.durationSelector = durationSelector;
  11405. this.subjectSelector = subjectSelector;
  11406. }
  11407. GroupByOperator.prototype.call = function (subscriber, source) {
  11408. return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector));
  11409. };
  11410. return GroupByOperator;
  11411. }());
  11412. /**
  11413. * We need this JSDoc comment for affecting ESDoc.
  11414. * @ignore
  11415. * @extends {Ignored}
  11416. */
  11417. var GroupBySubscriber = (function (_super) {
  11418. __extends(GroupBySubscriber, _super);
  11419. function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) {
  11420. _super.call(this, destination);
  11421. this.keySelector = keySelector;
  11422. this.elementSelector = elementSelector;
  11423. this.durationSelector = durationSelector;
  11424. this.subjectSelector = subjectSelector;
  11425. this.groups = null;
  11426. this.attemptedToUnsubscribe = false;
  11427. this.count = 0;
  11428. }
  11429. GroupBySubscriber.prototype._next = function (value) {
  11430. var key;
  11431. try {
  11432. key = this.keySelector(value);
  11433. }
  11434. catch (err) {
  11435. this.error(err);
  11436. return;
  11437. }
  11438. this._group(value, key);
  11439. };
  11440. GroupBySubscriber.prototype._group = function (value, key) {
  11441. var groups = this.groups;
  11442. if (!groups) {
  11443. groups = this.groups = typeof key === 'string' ? new FastMap() : new Map();
  11444. }
  11445. var group = groups.get(key);
  11446. var element;
  11447. if (this.elementSelector) {
  11448. try {
  11449. element = this.elementSelector(value);
  11450. }
  11451. catch (err) {
  11452. this.error(err);
  11453. }
  11454. }
  11455. else {
  11456. element = value;
  11457. }
  11458. if (!group) {
  11459. group = this.subjectSelector ? this.subjectSelector() : new Subject();
  11460. groups.set(key, group);
  11461. var groupedObservable = new GroupedObservable(key, group, this);
  11462. this.destination.next(groupedObservable);
  11463. if (this.durationSelector) {
  11464. var duration = void 0;
  11465. try {
  11466. duration = this.durationSelector(new GroupedObservable(key, group));
  11467. }
  11468. catch (err) {
  11469. this.error(err);
  11470. return;
  11471. }
  11472. this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
  11473. }
  11474. }
  11475. if (!group.closed) {
  11476. group.next(element);
  11477. }
  11478. };
  11479. GroupBySubscriber.prototype._error = function (err) {
  11480. var groups = this.groups;
  11481. if (groups) {
  11482. groups.forEach(function (group, key) {
  11483. group.error(err);
  11484. });
  11485. groups.clear();
  11486. }
  11487. this.destination.error(err);
  11488. };
  11489. GroupBySubscriber.prototype._complete = function () {
  11490. var groups = this.groups;
  11491. if (groups) {
  11492. groups.forEach(function (group, key) {
  11493. group.complete();
  11494. });
  11495. groups.clear();
  11496. }
  11497. this.destination.complete();
  11498. };
  11499. GroupBySubscriber.prototype.removeGroup = function (key) {
  11500. this.groups.delete(key);
  11501. };
  11502. GroupBySubscriber.prototype.unsubscribe = function () {
  11503. if (!this.closed) {
  11504. this.attemptedToUnsubscribe = true;
  11505. if (this.count === 0) {
  11506. _super.prototype.unsubscribe.call(this);
  11507. }
  11508. }
  11509. };
  11510. return GroupBySubscriber;
  11511. }(Subscriber));
  11512. /**
  11513. * We need this JSDoc comment for affecting ESDoc.
  11514. * @ignore
  11515. * @extends {Ignored}
  11516. */
  11517. var GroupDurationSubscriber = (function (_super) {
  11518. __extends(GroupDurationSubscriber, _super);
  11519. function GroupDurationSubscriber(key, group, parent) {
  11520. _super.call(this, group);
  11521. this.key = key;
  11522. this.group = group;
  11523. this.parent = parent;
  11524. }
  11525. GroupDurationSubscriber.prototype._next = function (value) {
  11526. this.complete();
  11527. };
  11528. /** @deprecated internal use only */ GroupDurationSubscriber.prototype._unsubscribe = function () {
  11529. var _a = this, parent = _a.parent, key = _a.key;
  11530. this.key = this.parent = null;
  11531. if (parent) {
  11532. parent.removeGroup(key);
  11533. }
  11534. };
  11535. return GroupDurationSubscriber;
  11536. }(Subscriber));
  11537. /**
  11538. * An Observable representing values belonging to the same group represented by
  11539. * a common key. The values emitted by a GroupedObservable come from the source
  11540. * Observable. The common key is available as the field `key` on a
  11541. * GroupedObservable instance.
  11542. *
  11543. * @class GroupedObservable<K, T>
  11544. */
  11545. var GroupedObservable = (function (_super) {
  11546. __extends(GroupedObservable, _super);
  11547. function GroupedObservable(key, groupSubject, refCountSubscription) {
  11548. _super.call(this);
  11549. this.key = key;
  11550. this.groupSubject = groupSubject;
  11551. this.refCountSubscription = refCountSubscription;
  11552. }
  11553. /** @deprecated internal use only */ GroupedObservable.prototype._subscribe = function (subscriber) {
  11554. var subscription = new Subscription();
  11555. var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject;
  11556. if (refCountSubscription && !refCountSubscription.closed) {
  11557. subscription.add(new InnerRefCountSubscription(refCountSubscription));
  11558. }
  11559. subscription.add(groupSubject.subscribe(subscriber));
  11560. return subscription;
  11561. };
  11562. return GroupedObservable;
  11563. }(Observable));
  11564. /**
  11565. * We need this JSDoc comment for affecting ESDoc.
  11566. * @ignore
  11567. * @extends {Ignored}
  11568. */
  11569. var InnerRefCountSubscription = (function (_super) {
  11570. __extends(InnerRefCountSubscription, _super);
  11571. function InnerRefCountSubscription(parent) {
  11572. _super.call(this);
  11573. this.parent = parent;
  11574. parent.count++;
  11575. }
  11576. InnerRefCountSubscription.prototype.unsubscribe = function () {
  11577. var parent = this.parent;
  11578. if (!parent.closed && !this.closed) {
  11579. _super.prototype.unsubscribe.call(this);
  11580. parent.count -= 1;
  11581. if (parent.count === 0 && parent.attemptedToUnsubscribe) {
  11582. parent.unsubscribe();
  11583. }
  11584. }
  11585. };
  11586. return InnerRefCountSubscription;
  11587. }(Subscription));
  11588. /* tslint:enable:max-line-length */
  11589. /**
  11590. * Groups the items emitted by an Observable according to a specified criterion,
  11591. * and emits these grouped items as `GroupedObservables`, one
  11592. * {@link GroupedObservable} per group.
  11593. *
  11594. * <img src="./img/groupBy.png" width="100%">
  11595. *
  11596. * @example <caption>Group objects by id and return as array</caption>
  11597. * Observable.of<Obj>({id: 1, name: 'aze1'},
  11598. * {id: 2, name: 'sf2'},
  11599. * {id: 2, name: 'dg2'},
  11600. * {id: 1, name: 'erg1'},
  11601. * {id: 1, name: 'df1'},
  11602. * {id: 2, name: 'sfqfb2'},
  11603. * {id: 3, name: 'qfs3'},
  11604. * {id: 2, name: 'qsgqsfg2'}
  11605. * )
  11606. * .groupBy(p => p.id)
  11607. * .flatMap( (group$) => group$.reduce((acc, cur) => [...acc, cur], []))
  11608. * .subscribe(p => console.log(p));
  11609. *
  11610. * // displays:
  11611. * // [ { id: 1, name: 'aze1' },
  11612. * // { id: 1, name: 'erg1' },
  11613. * // { id: 1, name: 'df1' } ]
  11614. * //
  11615. * // [ { id: 2, name: 'sf2' },
  11616. * // { id: 2, name: 'dg2' },
  11617. * // { id: 2, name: 'sfqfb2' },
  11618. * // { id: 2, name: 'qsgqsfg2' } ]
  11619. * //
  11620. * // [ { id: 3, name: 'qfs3' } ]
  11621. *
  11622. * @example <caption>Pivot data on the id field</caption>
  11623. * Observable.of<Obj>({id: 1, name: 'aze1'},
  11624. * {id: 2, name: 'sf2'},
  11625. * {id: 2, name: 'dg2'},
  11626. * {id: 1, name: 'erg1'},
  11627. * {id: 1, name: 'df1'},
  11628. * {id: 2, name: 'sfqfb2'},
  11629. * {id: 3, name: 'qfs1'},
  11630. * {id: 2, name: 'qsgqsfg2'}
  11631. * )
  11632. * .groupBy(p => p.id, p => p.name)
  11633. * .flatMap( (group$) => group$.reduce((acc, cur) => [...acc, cur], ["" + group$.key]))
  11634. * .map(arr => ({'id': parseInt(arr[0]), 'values': arr.slice(1)}))
  11635. * .subscribe(p => console.log(p));
  11636. *
  11637. * // displays:
  11638. * // { id: 1, values: [ 'aze1', 'erg1', 'df1' ] }
  11639. * // { id: 2, values: [ 'sf2', 'dg2', 'sfqfb2', 'qsgqsfg2' ] }
  11640. * // { id: 3, values: [ 'qfs1' ] }
  11641. *
  11642. * @param {function(value: T): K} keySelector A function that extracts the key
  11643. * for each item.
  11644. * @param {function(value: T): R} [elementSelector] A function that extracts the
  11645. * return element for each item.
  11646. * @param {function(grouped: GroupedObservable<K,R>): Observable<any>} [durationSelector]
  11647. * A function that returns an Observable to determine how long each group should
  11648. * exist.
  11649. * @return {Observable<GroupedObservable<K,R>>} An Observable that emits
  11650. * GroupedObservables, each of which corresponds to a unique key value and each
  11651. * of which emits those items from the source Observable that share that key
  11652. * value.
  11653. * @method groupBy
  11654. * @owner Observable
  11655. */
  11656. function groupBy$$1(keySelector, elementSelector, durationSelector, subjectSelector) {
  11657. return groupBy$1(keySelector, elementSelector, durationSelector, subjectSelector)(this);
  11658. }
  11659. Observable.prototype.groupBy = groupBy$$1;
  11660. /**
  11661. * Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`.
  11662. *
  11663. * <img src="./img/ignoreElements.png" width="100%">
  11664. *
  11665. * @return {Observable} An empty Observable that only calls `complete`
  11666. * or `error`, based on which one is called by the source Observable.
  11667. * @method ignoreElements
  11668. * @owner Observable
  11669. */
  11670. function ignoreElements$1() {
  11671. return function ignoreElementsOperatorFunction(source) {
  11672. return source.lift(new IgnoreElementsOperator());
  11673. };
  11674. }
  11675. var IgnoreElementsOperator = (function () {
  11676. function IgnoreElementsOperator() {
  11677. }
  11678. IgnoreElementsOperator.prototype.call = function (subscriber, source) {
  11679. return source.subscribe(new IgnoreElementsSubscriber(subscriber));
  11680. };
  11681. return IgnoreElementsOperator;
  11682. }());
  11683. /**
  11684. * We need this JSDoc comment for affecting ESDoc.
  11685. * @ignore
  11686. * @extends {Ignored}
  11687. */
  11688. var IgnoreElementsSubscriber = (function (_super) {
  11689. __extends(IgnoreElementsSubscriber, _super);
  11690. function IgnoreElementsSubscriber() {
  11691. _super.apply(this, arguments);
  11692. }
  11693. IgnoreElementsSubscriber.prototype._next = function (unused) {
  11694. noop();
  11695. };
  11696. return IgnoreElementsSubscriber;
  11697. }(Subscriber));
  11698. /**
  11699. * Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`.
  11700. *
  11701. * <img src="./img/ignoreElements.png" width="100%">
  11702. *
  11703. * @return {Observable} An empty Observable that only calls `complete`
  11704. * or `error`, based on which one is called by the source Observable.
  11705. * @method ignoreElements
  11706. * @owner Observable
  11707. */
  11708. function ignoreElements$$1() {
  11709. return ignoreElements$1()(this);
  11710. }
  11711. Observable.prototype.ignoreElements = ignoreElements$$1;
  11712. function isEmpty$1() {
  11713. return function (source) { return source.lift(new IsEmptyOperator()); };
  11714. }
  11715. var IsEmptyOperator = (function () {
  11716. function IsEmptyOperator() {
  11717. }
  11718. IsEmptyOperator.prototype.call = function (observer, source) {
  11719. return source.subscribe(new IsEmptySubscriber(observer));
  11720. };
  11721. return IsEmptyOperator;
  11722. }());
  11723. /**
  11724. * We need this JSDoc comment for affecting ESDoc.
  11725. * @ignore
  11726. * @extends {Ignored}
  11727. */
  11728. var IsEmptySubscriber = (function (_super) {
  11729. __extends(IsEmptySubscriber, _super);
  11730. function IsEmptySubscriber(destination) {
  11731. _super.call(this, destination);
  11732. }
  11733. IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) {
  11734. var destination = this.destination;
  11735. destination.next(isEmpty);
  11736. destination.complete();
  11737. };
  11738. IsEmptySubscriber.prototype._next = function (value) {
  11739. this.notifyComplete(false);
  11740. };
  11741. IsEmptySubscriber.prototype._complete = function () {
  11742. this.notifyComplete(true);
  11743. };
  11744. return IsEmptySubscriber;
  11745. }(Subscriber));
  11746. /**
  11747. * If the source Observable is empty it returns an Observable that emits true, otherwise it emits false.
  11748. *
  11749. * <img src="./img/isEmpty.png" width="100%">
  11750. *
  11751. * @return {Observable} An Observable that emits a Boolean.
  11752. * @method isEmpty
  11753. * @owner Observable
  11754. */
  11755. function isEmpty$$1() {
  11756. return isEmpty$1()(this);
  11757. }
  11758. Observable.prototype.isEmpty = isEmpty$$1;
  11759. /**
  11760. * Ignores source values for a duration determined by another Observable, then
  11761. * emits the most recent value from the source Observable, then repeats this
  11762. * process.
  11763. *
  11764. * <span class="informal">It's like {@link auditTime}, but the silencing
  11765. * duration is determined by a second Observable.</span>
  11766. *
  11767. * <img src="./img/audit.png" width="100%">
  11768. *
  11769. * `audit` is similar to `throttle`, but emits the last value from the silenced
  11770. * time window, instead of the first value. `audit` emits the most recent value
  11771. * from the source Observable on the output Observable as soon as its internal
  11772. * timer becomes disabled, and ignores source values while the timer is enabled.
  11773. * Initially, the timer is disabled. As soon as the first source value arrives,
  11774. * the timer is enabled by calling the `durationSelector` function with the
  11775. * source value, which returns the "duration" Observable. When the duration
  11776. * Observable emits a value or completes, the timer is disabled, then the most
  11777. * recent source value is emitted on the output Observable, and this process
  11778. * repeats for the next source value.
  11779. *
  11780. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  11781. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11782. * var result = clicks.audit(ev => Rx.Observable.interval(1000));
  11783. * result.subscribe(x => console.log(x));
  11784. *
  11785. * @see {@link auditTime}
  11786. * @see {@link debounce}
  11787. * @see {@link delayWhen}
  11788. * @see {@link sample}
  11789. * @see {@link throttle}
  11790. *
  11791. * @param {function(value: T): SubscribableOrPromise} durationSelector A function
  11792. * that receives a value from the source Observable, for computing the silencing
  11793. * duration, returned as an Observable or a Promise.
  11794. * @return {Observable<T>} An Observable that performs rate-limiting of
  11795. * emissions from the source Observable.
  11796. * @method audit
  11797. * @owner Observable
  11798. */
  11799. function audit$1(durationSelector) {
  11800. return function auditOperatorFunction(source) {
  11801. return source.lift(new AuditOperator(durationSelector));
  11802. };
  11803. }
  11804. var AuditOperator = (function () {
  11805. function AuditOperator(durationSelector) {
  11806. this.durationSelector = durationSelector;
  11807. }
  11808. AuditOperator.prototype.call = function (subscriber, source) {
  11809. return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
  11810. };
  11811. return AuditOperator;
  11812. }());
  11813. /**
  11814. * We need this JSDoc comment for affecting ESDoc.
  11815. * @ignore
  11816. * @extends {Ignored}
  11817. */
  11818. var AuditSubscriber = (function (_super) {
  11819. __extends(AuditSubscriber, _super);
  11820. function AuditSubscriber(destination, durationSelector) {
  11821. _super.call(this, destination);
  11822. this.durationSelector = durationSelector;
  11823. this.hasValue = false;
  11824. }
  11825. AuditSubscriber.prototype._next = function (value) {
  11826. this.value = value;
  11827. this.hasValue = true;
  11828. if (!this.throttled) {
  11829. var duration = tryCatch(this.durationSelector)(value);
  11830. if (duration === errorObject) {
  11831. this.destination.error(errorObject.e);
  11832. }
  11833. else {
  11834. var innerSubscription = subscribeToResult(this, duration);
  11835. if (innerSubscription.closed) {
  11836. this.clearThrottle();
  11837. }
  11838. else {
  11839. this.add(this.throttled = innerSubscription);
  11840. }
  11841. }
  11842. }
  11843. };
  11844. AuditSubscriber.prototype.clearThrottle = function () {
  11845. var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
  11846. if (throttled) {
  11847. this.remove(throttled);
  11848. this.throttled = null;
  11849. throttled.unsubscribe();
  11850. }
  11851. if (hasValue) {
  11852. this.value = null;
  11853. this.hasValue = false;
  11854. this.destination.next(value);
  11855. }
  11856. };
  11857. AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
  11858. this.clearThrottle();
  11859. };
  11860. AuditSubscriber.prototype.notifyComplete = function () {
  11861. this.clearThrottle();
  11862. };
  11863. return AuditSubscriber;
  11864. }(OuterSubscriber));
  11865. /**
  11866. * Ignores source values for a duration determined by another Observable, then
  11867. * emits the most recent value from the source Observable, then repeats this
  11868. * process.
  11869. *
  11870. * <span class="informal">It's like {@link auditTime}, but the silencing
  11871. * duration is determined by a second Observable.</span>
  11872. *
  11873. * <img src="./img/audit.png" width="100%">
  11874. *
  11875. * `audit` is similar to `throttle`, but emits the last value from the silenced
  11876. * time window, instead of the first value. `audit` emits the most recent value
  11877. * from the source Observable on the output Observable as soon as its internal
  11878. * timer becomes disabled, and ignores source values while the timer is enabled.
  11879. * Initially, the timer is disabled. As soon as the first source value arrives,
  11880. * the timer is enabled by calling the `durationSelector` function with the
  11881. * source value, which returns the "duration" Observable. When the duration
  11882. * Observable emits a value or completes, the timer is disabled, then the most
  11883. * recent source value is emitted on the output Observable, and this process
  11884. * repeats for the next source value.
  11885. *
  11886. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  11887. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11888. * var result = clicks.audit(ev => Rx.Observable.interval(1000));
  11889. * result.subscribe(x => console.log(x));
  11890. *
  11891. * @see {@link auditTime}
  11892. * @see {@link debounce}
  11893. * @see {@link delayWhen}
  11894. * @see {@link sample}
  11895. * @see {@link throttle}
  11896. *
  11897. * @param {function(value: T): SubscribableOrPromise} durationSelector A function
  11898. * that receives a value from the source Observable, for computing the silencing
  11899. * duration, returned as an Observable or a Promise.
  11900. * @return {Observable<T>} An Observable that performs rate-limiting of
  11901. * emissions from the source Observable.
  11902. * @method audit
  11903. * @owner Observable
  11904. */
  11905. function audit$$1(durationSelector) {
  11906. return audit$1(durationSelector)(this);
  11907. }
  11908. Observable.prototype.audit = audit$$1;
  11909. /**
  11910. * Ignores source values for `duration` milliseconds, then emits the most recent
  11911. * value from the source Observable, then repeats this process.
  11912. *
  11913. * <span class="informal">When it sees a source values, it ignores that plus
  11914. * the next ones for `duration` milliseconds, and then it emits the most recent
  11915. * value from the source.</span>
  11916. *
  11917. * <img src="./img/auditTime.png" width="100%">
  11918. *
  11919. * `auditTime` is similar to `throttleTime`, but emits the last value from the
  11920. * silenced time window, instead of the first value. `auditTime` emits the most
  11921. * recent value from the source Observable on the output Observable as soon as
  11922. * its internal timer becomes disabled, and ignores source values while the
  11923. * timer is enabled. Initially, the timer is disabled. As soon as the first
  11924. * source value arrives, the timer is enabled. After `duration` milliseconds (or
  11925. * the time unit determined internally by the optional `scheduler`) has passed,
  11926. * the timer is disabled, then the most recent source value is emitted on the
  11927. * output Observable, and this process repeats for the next source value.
  11928. * Optionally takes a {@link IScheduler} for managing timers.
  11929. *
  11930. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  11931. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11932. * var result = clicks.auditTime(1000);
  11933. * result.subscribe(x => console.log(x));
  11934. *
  11935. * @see {@link audit}
  11936. * @see {@link debounceTime}
  11937. * @see {@link delay}
  11938. * @see {@link sampleTime}
  11939. * @see {@link throttleTime}
  11940. *
  11941. * @param {number} duration Time to wait before emitting the most recent source
  11942. * value, measured in milliseconds or the time unit determined internally
  11943. * by the optional `scheduler`.
  11944. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  11945. * managing the timers that handle the rate-limiting behavior.
  11946. * @return {Observable<T>} An Observable that performs rate-limiting of
  11947. * emissions from the source Observable.
  11948. * @method auditTime
  11949. * @owner Observable
  11950. */
  11951. function auditTime$1(duration, scheduler) {
  11952. if (scheduler === void 0) { scheduler = async; }
  11953. return audit$1(function () { return timer(duration, scheduler); });
  11954. }
  11955. /**
  11956. * Ignores source values for `duration` milliseconds, then emits the most recent
  11957. * value from the source Observable, then repeats this process.
  11958. *
  11959. * <span class="informal">When it sees a source values, it ignores that plus
  11960. * the next ones for `duration` milliseconds, and then it emits the most recent
  11961. * value from the source.</span>
  11962. *
  11963. * <img src="./img/auditTime.png" width="100%">
  11964. *
  11965. * `auditTime` is similar to `throttleTime`, but emits the last value from the
  11966. * silenced time window, instead of the first value. `auditTime` emits the most
  11967. * recent value from the source Observable on the output Observable as soon as
  11968. * its internal timer becomes disabled, and ignores source values while the
  11969. * timer is enabled. Initially, the timer is disabled. As soon as the first
  11970. * source value arrives, the timer is enabled. After `duration` milliseconds (or
  11971. * the time unit determined internally by the optional `scheduler`) has passed,
  11972. * the timer is disabled, then the most recent source value is emitted on the
  11973. * output Observable, and this process repeats for the next source value.
  11974. * Optionally takes a {@link IScheduler} for managing timers.
  11975. *
  11976. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  11977. * var clicks = Rx.Observable.fromEvent(document, 'click');
  11978. * var result = clicks.auditTime(1000);
  11979. * result.subscribe(x => console.log(x));
  11980. *
  11981. * @see {@link audit}
  11982. * @see {@link debounceTime}
  11983. * @see {@link delay}
  11984. * @see {@link sampleTime}
  11985. * @see {@link throttleTime}
  11986. *
  11987. * @param {number} duration Time to wait before emitting the most recent source
  11988. * value, measured in milliseconds or the time unit determined internally
  11989. * by the optional `scheduler`.
  11990. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  11991. * managing the timers that handle the rate-limiting behavior.
  11992. * @return {Observable<T>} An Observable that performs rate-limiting of
  11993. * emissions from the source Observable.
  11994. * @method auditTime
  11995. * @owner Observable
  11996. */
  11997. function auditTime$$1(duration, scheduler) {
  11998. if (scheduler === void 0) { scheduler = async; }
  11999. return auditTime$1(duration, scheduler)(this);
  12000. }
  12001. Observable.prototype.auditTime = auditTime$$1;
  12002. /* tslint:enable:max-line-length */
  12003. /**
  12004. * Returns an Observable that emits only the last item emitted by the source Observable.
  12005. * It optionally takes a predicate function as a parameter, in which case, rather than emitting
  12006. * the last item from the source Observable, the resulting Observable will emit the last item
  12007. * from the source Observable that satisfies the predicate.
  12008. *
  12009. * <img src="./img/last.png" width="100%">
  12010. *
  12011. * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
  12012. * callback if the Observable completes before any `next` notification was sent.
  12013. * @param {function} predicate - The condition any source emitted item has to satisfy.
  12014. * @return {Observable} An Observable that emits only the last item satisfying the given condition
  12015. * from the source, or an NoSuchElementException if no such items are emitted.
  12016. * @throws - Throws if no items that match the predicate are emitted by the source Observable.
  12017. * @method last
  12018. * @owner Observable
  12019. */
  12020. function last$1(predicate, resultSelector, defaultValue) {
  12021. return function (source) { return source.lift(new LastOperator(predicate, resultSelector, defaultValue, source)); };
  12022. }
  12023. var LastOperator = (function () {
  12024. function LastOperator(predicate, resultSelector, defaultValue, source) {
  12025. this.predicate = predicate;
  12026. this.resultSelector = resultSelector;
  12027. this.defaultValue = defaultValue;
  12028. this.source = source;
  12029. }
  12030. LastOperator.prototype.call = function (observer, source) {
  12031. return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
  12032. };
  12033. return LastOperator;
  12034. }());
  12035. /**
  12036. * We need this JSDoc comment for affecting ESDoc.
  12037. * @ignore
  12038. * @extends {Ignored}
  12039. */
  12040. var LastSubscriber = (function (_super) {
  12041. __extends(LastSubscriber, _super);
  12042. function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
  12043. _super.call(this, destination);
  12044. this.predicate = predicate;
  12045. this.resultSelector = resultSelector;
  12046. this.defaultValue = defaultValue;
  12047. this.source = source;
  12048. this.hasValue = false;
  12049. this.index = 0;
  12050. if (typeof defaultValue !== 'undefined') {
  12051. this.lastValue = defaultValue;
  12052. this.hasValue = true;
  12053. }
  12054. }
  12055. LastSubscriber.prototype._next = function (value) {
  12056. var index = this.index++;
  12057. if (this.predicate) {
  12058. this._tryPredicate(value, index);
  12059. }
  12060. else {
  12061. if (this.resultSelector) {
  12062. this._tryResultSelector(value, index);
  12063. return;
  12064. }
  12065. this.lastValue = value;
  12066. this.hasValue = true;
  12067. }
  12068. };
  12069. LastSubscriber.prototype._tryPredicate = function (value, index) {
  12070. var result;
  12071. try {
  12072. result = this.predicate(value, index, this.source);
  12073. }
  12074. catch (err) {
  12075. this.destination.error(err);
  12076. return;
  12077. }
  12078. if (result) {
  12079. if (this.resultSelector) {
  12080. this._tryResultSelector(value, index);
  12081. return;
  12082. }
  12083. this.lastValue = value;
  12084. this.hasValue = true;
  12085. }
  12086. };
  12087. LastSubscriber.prototype._tryResultSelector = function (value, index) {
  12088. var result;
  12089. try {
  12090. result = this.resultSelector(value, index);
  12091. }
  12092. catch (err) {
  12093. this.destination.error(err);
  12094. return;
  12095. }
  12096. this.lastValue = result;
  12097. this.hasValue = true;
  12098. };
  12099. LastSubscriber.prototype._complete = function () {
  12100. var destination = this.destination;
  12101. if (this.hasValue) {
  12102. destination.next(this.lastValue);
  12103. destination.complete();
  12104. }
  12105. else {
  12106. destination.error(new EmptyError);
  12107. }
  12108. };
  12109. return LastSubscriber;
  12110. }(Subscriber));
  12111. /* tslint:enable:max-line-length */
  12112. /**
  12113. * Returns an Observable that emits only the last item emitted by the source Observable.
  12114. * It optionally takes a predicate function as a parameter, in which case, rather than emitting
  12115. * the last item from the source Observable, the resulting Observable will emit the last item
  12116. * from the source Observable that satisfies the predicate.
  12117. *
  12118. * <img src="./img/last.png" width="100%">
  12119. *
  12120. * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
  12121. * callback if the Observable completes before any `next` notification was sent.
  12122. * @param {function} predicate - The condition any source emitted item has to satisfy.
  12123. * @return {Observable} An Observable that emits only the last item satisfying the given condition
  12124. * from the source, or an NoSuchElementException if no such items are emitted.
  12125. * @throws - Throws if no items that match the predicate are emitted by the source Observable.
  12126. * @method last
  12127. * @owner Observable
  12128. */
  12129. function last$$1(predicate, resultSelector, defaultValue) {
  12130. return last$1(predicate, resultSelector, defaultValue)(this);
  12131. }
  12132. Observable.prototype.last = last$$1;
  12133. /**
  12134. * @param func
  12135. * @return {Observable<R>}
  12136. * @method let
  12137. * @owner Observable
  12138. */
  12139. function letProto(func) {
  12140. return func(this);
  12141. }
  12142. Observable.prototype.let = letProto;
  12143. Observable.prototype.letBind = letProto;
  12144. /**
  12145. * Returns an Observable that emits whether or not every item of the source satisfies the condition specified.
  12146. *
  12147. * @example <caption>A simple example emitting true if all elements are less than 5, false otherwise</caption>
  12148. * Observable.of(1, 2, 3, 4, 5, 6)
  12149. * .every(x => x < 5)
  12150. * .subscribe(x => console.log(x)); // -> false
  12151. *
  12152. * @param {function} predicate A function for determining if an item meets a specified condition.
  12153. * @param {any} [thisArg] Optional object to use for `this` in the callback.
  12154. * @return {Observable} An Observable of booleans that determines if all items of the source Observable meet the condition specified.
  12155. * @method every
  12156. * @owner Observable
  12157. */
  12158. function every$1(predicate, thisArg) {
  12159. return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); };
  12160. }
  12161. var EveryOperator = (function () {
  12162. function EveryOperator(predicate, thisArg, source) {
  12163. this.predicate = predicate;
  12164. this.thisArg = thisArg;
  12165. this.source = source;
  12166. }
  12167. EveryOperator.prototype.call = function (observer, source) {
  12168. return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
  12169. };
  12170. return EveryOperator;
  12171. }());
  12172. /**
  12173. * We need this JSDoc comment for affecting ESDoc.
  12174. * @ignore
  12175. * @extends {Ignored}
  12176. */
  12177. var EverySubscriber = (function (_super) {
  12178. __extends(EverySubscriber, _super);
  12179. function EverySubscriber(destination, predicate, thisArg, source) {
  12180. _super.call(this, destination);
  12181. this.predicate = predicate;
  12182. this.thisArg = thisArg;
  12183. this.source = source;
  12184. this.index = 0;
  12185. this.thisArg = thisArg || this;
  12186. }
  12187. EverySubscriber.prototype.notifyComplete = function (everyValueMatch) {
  12188. this.destination.next(everyValueMatch);
  12189. this.destination.complete();
  12190. };
  12191. EverySubscriber.prototype._next = function (value) {
  12192. var result = false;
  12193. try {
  12194. result = this.predicate.call(this.thisArg, value, this.index++, this.source);
  12195. }
  12196. catch (err) {
  12197. this.destination.error(err);
  12198. return;
  12199. }
  12200. if (!result) {
  12201. this.notifyComplete(false);
  12202. }
  12203. };
  12204. EverySubscriber.prototype._complete = function () {
  12205. this.notifyComplete(true);
  12206. };
  12207. return EverySubscriber;
  12208. }(Subscriber));
  12209. /**
  12210. * Returns an Observable that emits whether or not every item of the source satisfies the condition specified.
  12211. *
  12212. * @example <caption>A simple example emitting true if all elements are less than 5, false otherwise</caption>
  12213. * Observable.of(1, 2, 3, 4, 5, 6)
  12214. * .every(x => x < 5)
  12215. * .subscribe(x => console.log(x)); // -> false
  12216. *
  12217. * @param {function} predicate A function for determining if an item meets a specified condition.
  12218. * @param {any} [thisArg] Optional object to use for `this` in the callback.
  12219. * @return {Observable} An Observable of booleans that determines if all items of the source Observable meet the condition specified.
  12220. * @method every
  12221. * @owner Observable
  12222. */
  12223. function every$$1(predicate, thisArg) {
  12224. return every$1(predicate, thisArg)(this);
  12225. }
  12226. Observable.prototype.every = every$$1;
  12227. /**
  12228. * Applies a given `project` function to each value emitted by the source
  12229. * Observable, and emits the resulting values as an Observable.
  12230. *
  12231. * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
  12232. * it passes each source value through a transformation function to get
  12233. * corresponding output values.</span>
  12234. *
  12235. * <img src="./img/map.png" width="100%">
  12236. *
  12237. * Similar to the well known `Array.prototype.map` function, this operator
  12238. * applies a projection to each value and emits that projection in the output
  12239. * Observable.
  12240. *
  12241. * @example <caption>Map every click to the clientX position of that click</caption>
  12242. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12243. * var positions = clicks.map(ev => ev.clientX);
  12244. * positions.subscribe(x => console.log(x));
  12245. *
  12246. * @see {@link mapTo}
  12247. * @see {@link pluck}
  12248. *
  12249. * @param {function(value: T, index: number): R} project The function to apply
  12250. * to each `value` emitted by the source Observable. The `index` parameter is
  12251. * the number `i` for the i-th emission that has happened since the
  12252. * subscription, starting from the number `0`.
  12253. * @param {any} [thisArg] An optional argument to define what `this` is in the
  12254. * `project` function.
  12255. * @return {Observable<R>} An Observable that emits the values from the source
  12256. * Observable transformed by the given `project` function.
  12257. * @method map
  12258. * @owner Observable
  12259. */
  12260. function map$1(project, thisArg) {
  12261. return map(project, thisArg)(this);
  12262. }
  12263. Observable.prototype.map = map$1;
  12264. /**
  12265. * Emits the given constant value on the output Observable every time the source
  12266. * Observable emits a value.
  12267. *
  12268. * <span class="informal">Like {@link map}, but it maps every source value to
  12269. * the same output value every time.</span>
  12270. *
  12271. * <img src="./img/mapTo.png" width="100%">
  12272. *
  12273. * Takes a constant `value` as argument, and emits that whenever the source
  12274. * Observable emits a value. In other words, ignores the actual source value,
  12275. * and simply uses the emission moment to know when to emit the given `value`.
  12276. *
  12277. * @example <caption>Map every click to the string 'Hi'</caption>
  12278. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12279. * var greetings = clicks.mapTo('Hi');
  12280. * greetings.subscribe(x => console.log(x));
  12281. *
  12282. * @see {@link map}
  12283. *
  12284. * @param {any} value The value to map each source value to.
  12285. * @return {Observable} An Observable that emits the given `value` every time
  12286. * the source Observable emits something.
  12287. * @method mapTo
  12288. * @owner Observable
  12289. */
  12290. function mapTo$1(value) {
  12291. return function (source) { return source.lift(new MapToOperator(value)); };
  12292. }
  12293. var MapToOperator = (function () {
  12294. function MapToOperator(value) {
  12295. this.value = value;
  12296. }
  12297. MapToOperator.prototype.call = function (subscriber, source) {
  12298. return source.subscribe(new MapToSubscriber(subscriber, this.value));
  12299. };
  12300. return MapToOperator;
  12301. }());
  12302. /**
  12303. * We need this JSDoc comment for affecting ESDoc.
  12304. * @ignore
  12305. * @extends {Ignored}
  12306. */
  12307. var MapToSubscriber = (function (_super) {
  12308. __extends(MapToSubscriber, _super);
  12309. function MapToSubscriber(destination, value) {
  12310. _super.call(this, destination);
  12311. this.value = value;
  12312. }
  12313. MapToSubscriber.prototype._next = function (x) {
  12314. this.destination.next(this.value);
  12315. };
  12316. return MapToSubscriber;
  12317. }(Subscriber));
  12318. /**
  12319. * Emits the given constant value on the output Observable every time the source
  12320. * Observable emits a value.
  12321. *
  12322. * <span class="informal">Like {@link map}, but it maps every source value to
  12323. * the same output value every time.</span>
  12324. *
  12325. * <img src="./img/mapTo.png" width="100%">
  12326. *
  12327. * Takes a constant `value` as argument, and emits that whenever the source
  12328. * Observable emits a value. In other words, ignores the actual source value,
  12329. * and simply uses the emission moment to know when to emit the given `value`.
  12330. *
  12331. * @example <caption>Map every click to the string 'Hi'</caption>
  12332. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12333. * var greetings = clicks.mapTo('Hi');
  12334. * greetings.subscribe(x => console.log(x));
  12335. *
  12336. * @see {@link map}
  12337. *
  12338. * @param {any} value The value to map each source value to.
  12339. * @return {Observable} An Observable that emits the given `value` every time
  12340. * the source Observable emits something.
  12341. * @method mapTo
  12342. * @owner Observable
  12343. */
  12344. function mapTo$$1(value) {
  12345. return mapTo$1(value)(this);
  12346. }
  12347. Observable.prototype.mapTo = mapTo$$1;
  12348. /**
  12349. * Represents all of the notifications from the source Observable as `next`
  12350. * emissions marked with their original types within {@link Notification}
  12351. * objects.
  12352. *
  12353. * <span class="informal">Wraps `next`, `error` and `complete` emissions in
  12354. * {@link Notification} objects, emitted as `next` on the output Observable.
  12355. * </span>
  12356. *
  12357. * <img src="./img/materialize.png" width="100%">
  12358. *
  12359. * `materialize` returns an Observable that emits a `next` notification for each
  12360. * `next`, `error`, or `complete` emission of the source Observable. When the
  12361. * source Observable emits `complete`, the output Observable will emit `next` as
  12362. * a Notification of type "complete", and then it will emit `complete` as well.
  12363. * When the source Observable emits `error`, the output will emit `next` as a
  12364. * Notification of type "error", and then `complete`.
  12365. *
  12366. * This operator is useful for producing metadata of the source Observable, to
  12367. * be consumed as `next` emissions. Use it in conjunction with
  12368. * {@link dematerialize}.
  12369. *
  12370. * @example <caption>Convert a faulty Observable to an Observable of Notifications</caption>
  12371. * var letters = Rx.Observable.of('a', 'b', 13, 'd');
  12372. * var upperCase = letters.map(x => x.toUpperCase());
  12373. * var materialized = upperCase.materialize();
  12374. * materialized.subscribe(x => console.log(x));
  12375. *
  12376. * // Results in the following:
  12377. * // - Notification {kind: "N", value: "A", error: undefined, hasValue: true}
  12378. * // - Notification {kind: "N", value: "B", error: undefined, hasValue: true}
  12379. * // - Notification {kind: "E", value: undefined, error: TypeError:
  12380. * // x.toUpperCase is not a function at MapSubscriber.letters.map.x
  12381. * // [as project] (http://1…, hasValue: false}
  12382. *
  12383. * @see {@link Notification}
  12384. * @see {@link dematerialize}
  12385. *
  12386. * @return {Observable<Notification<T>>} An Observable that emits
  12387. * {@link Notification} objects that wrap the original emissions from the source
  12388. * Observable with metadata.
  12389. * @method materialize
  12390. * @owner Observable
  12391. */
  12392. function materialize$1() {
  12393. return function materializeOperatorFunction(source) {
  12394. return source.lift(new MaterializeOperator());
  12395. };
  12396. }
  12397. var MaterializeOperator = (function () {
  12398. function MaterializeOperator() {
  12399. }
  12400. MaterializeOperator.prototype.call = function (subscriber, source) {
  12401. return source.subscribe(new MaterializeSubscriber(subscriber));
  12402. };
  12403. return MaterializeOperator;
  12404. }());
  12405. /**
  12406. * We need this JSDoc comment for affecting ESDoc.
  12407. * @ignore
  12408. * @extends {Ignored}
  12409. */
  12410. var MaterializeSubscriber = (function (_super) {
  12411. __extends(MaterializeSubscriber, _super);
  12412. function MaterializeSubscriber(destination) {
  12413. _super.call(this, destination);
  12414. }
  12415. MaterializeSubscriber.prototype._next = function (value) {
  12416. this.destination.next(Notification.createNext(value));
  12417. };
  12418. MaterializeSubscriber.prototype._error = function (err) {
  12419. var destination = this.destination;
  12420. destination.next(Notification.createError(err));
  12421. destination.complete();
  12422. };
  12423. MaterializeSubscriber.prototype._complete = function () {
  12424. var destination = this.destination;
  12425. destination.next(Notification.createComplete());
  12426. destination.complete();
  12427. };
  12428. return MaterializeSubscriber;
  12429. }(Subscriber));
  12430. /**
  12431. * Represents all of the notifications from the source Observable as `next`
  12432. * emissions marked with their original types within {@link Notification}
  12433. * objects.
  12434. *
  12435. * <span class="informal">Wraps `next`, `error` and `complete` emissions in
  12436. * {@link Notification} objects, emitted as `next` on the output Observable.
  12437. * </span>
  12438. *
  12439. * <img src="./img/materialize.png" width="100%">
  12440. *
  12441. * `materialize` returns an Observable that emits a `next` notification for each
  12442. * `next`, `error`, or `complete` emission of the source Observable. When the
  12443. * source Observable emits `complete`, the output Observable will emit `next` as
  12444. * a Notification of type "complete", and then it will emit `complete` as well.
  12445. * When the source Observable emits `error`, the output will emit `next` as a
  12446. * Notification of type "error", and then `complete`.
  12447. *
  12448. * This operator is useful for producing metadata of the source Observable, to
  12449. * be consumed as `next` emissions. Use it in conjunction with
  12450. * {@link dematerialize}.
  12451. *
  12452. * @example <caption>Convert a faulty Observable to an Observable of Notifications</caption>
  12453. * var letters = Rx.Observable.of('a', 'b', 13, 'd');
  12454. * var upperCase = letters.map(x => x.toUpperCase());
  12455. * var materialized = upperCase.materialize();
  12456. * materialized.subscribe(x => console.log(x));
  12457. *
  12458. * // Results in the following:
  12459. * // - Notification {kind: "N", value: "A", error: undefined, hasValue: true}
  12460. * // - Notification {kind: "N", value: "B", error: undefined, hasValue: true}
  12461. * // - Notification {kind: "E", value: undefined, error: TypeError:
  12462. * // x.toUpperCase is not a function at MapSubscriber.letters.map.x
  12463. * // [as project] (http://1…, hasValue: false}
  12464. *
  12465. * @see {@link Notification}
  12466. * @see {@link dematerialize}
  12467. *
  12468. * @return {Observable<Notification<T>>} An Observable that emits
  12469. * {@link Notification} objects that wrap the original emissions from the source
  12470. * Observable with metadata.
  12471. * @method materialize
  12472. * @owner Observable
  12473. */
  12474. function materialize$$1() {
  12475. return materialize$1()(this);
  12476. }
  12477. Observable.prototype.materialize = materialize$$1;
  12478. /* tslint:enable:max-line-length */
  12479. /**
  12480. * Applies an accumulator function over the source Observable, and returns each
  12481. * intermediate result, with an optional seed value.
  12482. *
  12483. * <span class="informal">It's like {@link reduce}, but emits the current
  12484. * accumulation whenever the source emits a value.</span>
  12485. *
  12486. * <img src="./img/scan.png" width="100%">
  12487. *
  12488. * Combines together all values emitted on the source, using an accumulator
  12489. * function that knows how to join a new source value into the accumulation from
  12490. * the past. Is similar to {@link reduce}, but emits the intermediate
  12491. * accumulations.
  12492. *
  12493. * Returns an Observable that applies a specified `accumulator` function to each
  12494. * item emitted by the source Observable. If a `seed` value is specified, then
  12495. * that value will be used as the initial value for the accumulator. If no seed
  12496. * value is specified, the first item of the source is used as the seed.
  12497. *
  12498. * @example <caption>Count the number of click events</caption>
  12499. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12500. * var ones = clicks.mapTo(1);
  12501. * var seed = 0;
  12502. * var count = ones.scan((acc, one) => acc + one, seed);
  12503. * count.subscribe(x => console.log(x));
  12504. *
  12505. * @see {@link expand}
  12506. * @see {@link mergeScan}
  12507. * @see {@link reduce}
  12508. *
  12509. * @param {function(acc: R, value: T, index: number): R} accumulator
  12510. * The accumulator function called on each source value.
  12511. * @param {T|R} [seed] The initial accumulation value.
  12512. * @return {Observable<R>} An observable of the accumulated values.
  12513. * @method scan
  12514. * @owner Observable
  12515. */
  12516. function scan(accumulator, seed) {
  12517. var hasSeed = false;
  12518. // providing a seed of `undefined` *should* be valid and trigger
  12519. // hasSeed! so don't use `seed !== undefined` checks!
  12520. // For this reason, we have to check it here at the original call site
  12521. // otherwise inside Operator/Subscriber we won't know if `undefined`
  12522. // means they didn't provide anything or if they literally provided `undefined`
  12523. if (arguments.length >= 2) {
  12524. hasSeed = true;
  12525. }
  12526. return function scanOperatorFunction(source) {
  12527. return source.lift(new ScanOperator(accumulator, seed, hasSeed));
  12528. };
  12529. }
  12530. var ScanOperator = (function () {
  12531. function ScanOperator(accumulator, seed, hasSeed) {
  12532. if (hasSeed === void 0) { hasSeed = false; }
  12533. this.accumulator = accumulator;
  12534. this.seed = seed;
  12535. this.hasSeed = hasSeed;
  12536. }
  12537. ScanOperator.prototype.call = function (subscriber, source) {
  12538. return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
  12539. };
  12540. return ScanOperator;
  12541. }());
  12542. /**
  12543. * We need this JSDoc comment for affecting ESDoc.
  12544. * @ignore
  12545. * @extends {Ignored}
  12546. */
  12547. var ScanSubscriber = (function (_super) {
  12548. __extends(ScanSubscriber, _super);
  12549. function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
  12550. _super.call(this, destination);
  12551. this.accumulator = accumulator;
  12552. this._seed = _seed;
  12553. this.hasSeed = hasSeed;
  12554. this.index = 0;
  12555. }
  12556. Object.defineProperty(ScanSubscriber.prototype, "seed", {
  12557. get: function () {
  12558. return this._seed;
  12559. },
  12560. set: function (value) {
  12561. this.hasSeed = true;
  12562. this._seed = value;
  12563. },
  12564. enumerable: true,
  12565. configurable: true
  12566. });
  12567. ScanSubscriber.prototype._next = function (value) {
  12568. if (!this.hasSeed) {
  12569. this.seed = value;
  12570. this.destination.next(value);
  12571. }
  12572. else {
  12573. return this._tryNext(value);
  12574. }
  12575. };
  12576. ScanSubscriber.prototype._tryNext = function (value) {
  12577. var index = this.index++;
  12578. var result;
  12579. try {
  12580. result = this.accumulator(this.seed, value, index);
  12581. }
  12582. catch (err) {
  12583. this.destination.error(err);
  12584. }
  12585. this.seed = result;
  12586. this.destination.next(result);
  12587. };
  12588. return ScanSubscriber;
  12589. }(Subscriber));
  12590. /**
  12591. * Emits only the last `count` values emitted by the source Observable.
  12592. *
  12593. * <span class="informal">Remembers the latest `count` values, then emits those
  12594. * only when the source completes.</span>
  12595. *
  12596. * <img src="./img/takeLast.png" width="100%">
  12597. *
  12598. * `takeLast` returns an Observable that emits at most the last `count` values
  12599. * emitted by the source Observable. If the source emits fewer than `count`
  12600. * values then all of its values are emitted. This operator must wait until the
  12601. * `complete` notification emission from the source in order to emit the `next`
  12602. * values on the output Observable, because otherwise it is impossible to know
  12603. * whether or not more values will be emitted on the source. For this reason,
  12604. * all values are emitted synchronously, followed by the complete notification.
  12605. *
  12606. * @example <caption>Take the last 3 values of an Observable with many values</caption>
  12607. * var many = Rx.Observable.range(1, 100);
  12608. * var lastThree = many.takeLast(3);
  12609. * lastThree.subscribe(x => console.log(x));
  12610. *
  12611. * @see {@link take}
  12612. * @see {@link takeUntil}
  12613. * @see {@link takeWhile}
  12614. * @see {@link skip}
  12615. *
  12616. * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an
  12617. * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
  12618. *
  12619. * @param {number} count The maximum number of values to emit from the end of
  12620. * the sequence of values emitted by the source Observable.
  12621. * @return {Observable<T>} An Observable that emits at most the last count
  12622. * values emitted by the source Observable.
  12623. * @method takeLast
  12624. * @owner Observable
  12625. */
  12626. function takeLast(count) {
  12627. return function takeLastOperatorFunction(source) {
  12628. if (count === 0) {
  12629. return new EmptyObservable();
  12630. }
  12631. else {
  12632. return source.lift(new TakeLastOperator(count));
  12633. }
  12634. };
  12635. }
  12636. var TakeLastOperator = (function () {
  12637. function TakeLastOperator(total) {
  12638. this.total = total;
  12639. if (this.total < 0) {
  12640. throw new ArgumentOutOfRangeError;
  12641. }
  12642. }
  12643. TakeLastOperator.prototype.call = function (subscriber, source) {
  12644. return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
  12645. };
  12646. return TakeLastOperator;
  12647. }());
  12648. /**
  12649. * We need this JSDoc comment for affecting ESDoc.
  12650. * @ignore
  12651. * @extends {Ignored}
  12652. */
  12653. var TakeLastSubscriber = (function (_super) {
  12654. __extends(TakeLastSubscriber, _super);
  12655. function TakeLastSubscriber(destination, total) {
  12656. _super.call(this, destination);
  12657. this.total = total;
  12658. this.ring = new Array();
  12659. this.count = 0;
  12660. }
  12661. TakeLastSubscriber.prototype._next = function (value) {
  12662. var ring = this.ring;
  12663. var total = this.total;
  12664. var count = this.count++;
  12665. if (ring.length < total) {
  12666. ring.push(value);
  12667. }
  12668. else {
  12669. var index = count % total;
  12670. ring[index] = value;
  12671. }
  12672. };
  12673. TakeLastSubscriber.prototype._complete = function () {
  12674. var destination = this.destination;
  12675. var count = this.count;
  12676. if (count > 0) {
  12677. var total = this.count >= this.total ? this.total : this.count;
  12678. var ring = this.ring;
  12679. for (var i = 0; i < total; i++) {
  12680. var idx = (count++) % total;
  12681. destination.next(ring[idx]);
  12682. }
  12683. }
  12684. destination.complete();
  12685. };
  12686. return TakeLastSubscriber;
  12687. }(Subscriber));
  12688. /* tslint:enable:max-line-length */
  12689. /**
  12690. * Applies an accumulator function over the source Observable, and returns the
  12691. * accumulated result when the source completes, given an optional seed value.
  12692. *
  12693. * <span class="informal">Combines together all values emitted on the source,
  12694. * using an accumulator function that knows how to join a new source value into
  12695. * the accumulation from the past.</span>
  12696. *
  12697. * <img src="./img/reduce.png" width="100%">
  12698. *
  12699. * Like
  12700. * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
  12701. * `reduce` applies an `accumulator` function against an accumulation and each
  12702. * value of the source Observable (from the past) to reduce it to a single
  12703. * value, emitted on the output Observable. Note that `reduce` will only emit
  12704. * one value, only when the source Observable completes. It is equivalent to
  12705. * applying operator {@link scan} followed by operator {@link last}.
  12706. *
  12707. * Returns an Observable that applies a specified `accumulator` function to each
  12708. * item emitted by the source Observable. If a `seed` value is specified, then
  12709. * that value will be used as the initial value for the accumulator. If no seed
  12710. * value is specified, the first item of the source is used as the seed.
  12711. *
  12712. * @example <caption>Count the number of click events that happened in 5 seconds</caption>
  12713. * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click')
  12714. * .takeUntil(Rx.Observable.interval(5000));
  12715. * var ones = clicksInFiveSeconds.mapTo(1);
  12716. * var seed = 0;
  12717. * var count = ones.reduce((acc, one) => acc + one, seed);
  12718. * count.subscribe(x => console.log(x));
  12719. *
  12720. * @see {@link count}
  12721. * @see {@link expand}
  12722. * @see {@link mergeScan}
  12723. * @see {@link scan}
  12724. *
  12725. * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function
  12726. * called on each source value.
  12727. * @param {R} [seed] The initial accumulation value.
  12728. * @return {Observable<R>} An Observable that emits a single value that is the
  12729. * result of accumulating the values emitted by the source Observable.
  12730. * @method reduce
  12731. * @owner Observable
  12732. */
  12733. function reduce(accumulator, seed) {
  12734. // providing a seed of `undefined` *should* be valid and trigger
  12735. // hasSeed! so don't use `seed !== undefined` checks!
  12736. // For this reason, we have to check it here at the original call site
  12737. // otherwise inside Operator/Subscriber we won't know if `undefined`
  12738. // means they didn't provide anything or if they literally provided `undefined`
  12739. if (arguments.length >= 2) {
  12740. return function reduceOperatorFunctionWithSeed(source) {
  12741. return pipe(scan(accumulator, seed), takeLast(1), defaultIfEmpty$1(seed))(source);
  12742. };
  12743. }
  12744. return function reduceOperatorFunction(source) {
  12745. return pipe(scan(function (acc, value, index) {
  12746. return accumulator(acc, value, index + 1);
  12747. }), takeLast(1))(source);
  12748. };
  12749. }
  12750. /**
  12751. * The Max operator operates on an Observable that emits numbers (or items that can be compared with a provided function),
  12752. * and when source Observable completes it emits a single item: the item with the largest value.
  12753. *
  12754. * <img src="./img/max.png" width="100%">
  12755. *
  12756. * @example <caption>Get the maximal value of a series of numbers</caption>
  12757. * Rx.Observable.of(5, 4, 7, 2, 8)
  12758. * .max()
  12759. * .subscribe(x => console.log(x)); // -> 8
  12760. *
  12761. * @example <caption>Use a comparer function to get the maximal item</caption>
  12762. * interface Person {
  12763. * age: number,
  12764. * name: string
  12765. * }
  12766. * Observable.of<Person>({age: 7, name: 'Foo'},
  12767. * {age: 5, name: 'Bar'},
  12768. * {age: 9, name: 'Beer'})
  12769. * .max<Person>((a: Person, b: Person) => a.age < b.age ? -1 : 1)
  12770. * .subscribe((x: Person) => console.log(x.name)); // -> 'Beer'
  12771. * }
  12772. *
  12773. * @see {@link min}
  12774. *
  12775. * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the
  12776. * value of two items.
  12777. * @return {Observable} An Observable that emits item with the largest value.
  12778. * @method max
  12779. * @owner Observable
  12780. */
  12781. function max$1(comparer) {
  12782. var max = (typeof comparer === 'function')
  12783. ? function (x, y) { return comparer(x, y) > 0 ? x : y; }
  12784. : function (x, y) { return x > y ? x : y; };
  12785. return reduce(max);
  12786. }
  12787. /**
  12788. * The Max operator operates on an Observable that emits numbers (or items that can be compared with a provided function),
  12789. * and when source Observable completes it emits a single item: the item with the largest value.
  12790. *
  12791. * <img src="./img/max.png" width="100%">
  12792. *
  12793. * @example <caption>Get the maximal value of a series of numbers</caption>
  12794. * Rx.Observable.of(5, 4, 7, 2, 8)
  12795. * .max()
  12796. * .subscribe(x => console.log(x)); // -> 8
  12797. *
  12798. * @example <caption>Use a comparer function to get the maximal item</caption>
  12799. * interface Person {
  12800. * age: number,
  12801. * name: string
  12802. * }
  12803. * Observable.of<Person>({age: 7, name: 'Foo'},
  12804. * {age: 5, name: 'Bar'},
  12805. * {age: 9, name: 'Beer'})
  12806. * .max<Person>((a: Person, b: Person) => a.age < b.age ? -1 : 1)
  12807. * .subscribe((x: Person) => console.log(x.name)); // -> 'Beer'
  12808. * }
  12809. *
  12810. * @see {@link min}
  12811. *
  12812. * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the
  12813. * value of two items.
  12814. * @return {Observable} An Observable that emits item with the largest value.
  12815. * @method max
  12816. * @owner Observable
  12817. */
  12818. function max$$1(comparer) {
  12819. return max$1(comparer)(this);
  12820. }
  12821. Observable.prototype.max = max$$1;
  12822. /* tslint:enable:max-line-length */
  12823. /**
  12824. * Creates an output Observable which concurrently emits all values from every
  12825. * given input Observable.
  12826. *
  12827. * <span class="informal">Flattens multiple Observables together by blending
  12828. * their values into one Observable.</span>
  12829. *
  12830. * <img src="./img/merge.png" width="100%">
  12831. *
  12832. * `merge` subscribes to each given input Observable (either the source or an
  12833. * Observable given as argument), and simply forwards (without doing any
  12834. * transformation) all the values from all the input Observables to the output
  12835. * Observable. The output Observable only completes once all input Observables
  12836. * have completed. Any error delivered by an input Observable will be immediately
  12837. * emitted on the output Observable.
  12838. *
  12839. * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
  12840. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12841. * var timer = Rx.Observable.interval(1000);
  12842. * var clicksOrTimer = clicks.merge(timer);
  12843. * clicksOrTimer.subscribe(x => console.log(x));
  12844. *
  12845. * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
  12846. * var timer1 = Rx.Observable.interval(1000).take(10);
  12847. * var timer2 = Rx.Observable.interval(2000).take(6);
  12848. * var timer3 = Rx.Observable.interval(500).take(10);
  12849. * var concurrent = 2; // the argument
  12850. * var merged = timer1.merge(timer2, timer3, concurrent);
  12851. * merged.subscribe(x => console.log(x));
  12852. *
  12853. * @see {@link mergeAll}
  12854. * @see {@link mergeMap}
  12855. * @see {@link mergeMapTo}
  12856. * @see {@link mergeScan}
  12857. *
  12858. * @param {ObservableInput} other An input Observable to merge with the source
  12859. * Observable. More than one input Observables may be given as argument.
  12860. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  12861. * Observables being subscribed to concurrently.
  12862. * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
  12863. * concurrency of input Observables.
  12864. * @return {Observable} An Observable that emits items that are the result of
  12865. * every input Observable.
  12866. * @method merge
  12867. * @owner Observable
  12868. */
  12869. function merge$2() {
  12870. var observables = [];
  12871. for (var _i = 0; _i < arguments.length; _i++) {
  12872. observables[_i - 0] = arguments[_i];
  12873. }
  12874. return function (source) { return source.lift.call(merge.apply(void 0, [source].concat(observables))); };
  12875. }
  12876. /* tslint:enable:max-line-length */
  12877. /**
  12878. * Creates an output Observable which concurrently emits all values from every
  12879. * given input Observable.
  12880. *
  12881. * <span class="informal">Flattens multiple Observables together by blending
  12882. * their values into one Observable.</span>
  12883. *
  12884. * <img src="./img/merge.png" width="100%">
  12885. *
  12886. * `merge` subscribes to each given input Observable (either the source or an
  12887. * Observable given as argument), and simply forwards (without doing any
  12888. * transformation) all the values from all the input Observables to the output
  12889. * Observable. The output Observable only completes once all input Observables
  12890. * have completed. Any error delivered by an input Observable will be immediately
  12891. * emitted on the output Observable.
  12892. *
  12893. * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
  12894. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12895. * var timer = Rx.Observable.interval(1000);
  12896. * var clicksOrTimer = clicks.merge(timer);
  12897. * clicksOrTimer.subscribe(x => console.log(x));
  12898. *
  12899. * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
  12900. * var timer1 = Rx.Observable.interval(1000).take(10);
  12901. * var timer2 = Rx.Observable.interval(2000).take(6);
  12902. * var timer3 = Rx.Observable.interval(500).take(10);
  12903. * var concurrent = 2; // the argument
  12904. * var merged = timer1.merge(timer2, timer3, concurrent);
  12905. * merged.subscribe(x => console.log(x));
  12906. *
  12907. * @see {@link mergeAll}
  12908. * @see {@link mergeMap}
  12909. * @see {@link mergeMapTo}
  12910. * @see {@link mergeScan}
  12911. *
  12912. * @param {ObservableInput} other An input Observable to merge with the source
  12913. * Observable. More than one input Observables may be given as argument.
  12914. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  12915. * Observables being subscribed to concurrently.
  12916. * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
  12917. * concurrency of input Observables.
  12918. * @return {Observable} An Observable that emits items that are the result of
  12919. * every input Observable.
  12920. * @method merge
  12921. * @owner Observable
  12922. */
  12923. function merge$1() {
  12924. var observables = [];
  12925. for (var _i = 0; _i < arguments.length; _i++) {
  12926. observables[_i - 0] = arguments[_i];
  12927. }
  12928. return merge$2.apply(void 0, observables)(this);
  12929. }
  12930. Observable.prototype.merge = merge$1;
  12931. /**
  12932. * Converts a higher-order Observable into a first-order Observable which
  12933. * concurrently delivers all values that are emitted on the inner Observables.
  12934. *
  12935. * <span class="informal">Flattens an Observable-of-Observables.</span>
  12936. *
  12937. * <img src="./img/mergeAll.png" width="100%">
  12938. *
  12939. * `mergeAll` subscribes to an Observable that emits Observables, also known as
  12940. * a higher-order Observable. Each time it observes one of these emitted inner
  12941. * Observables, it subscribes to that and delivers all the values from the
  12942. * inner Observable on the output Observable. The output Observable only
  12943. * completes once all inner Observables have completed. Any error delivered by
  12944. * a inner Observable will be immediately emitted on the output Observable.
  12945. *
  12946. * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
  12947. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12948. * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
  12949. * var firstOrder = higherOrder.mergeAll();
  12950. * firstOrder.subscribe(x => console.log(x));
  12951. *
  12952. * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
  12953. * var clicks = Rx.Observable.fromEvent(document, 'click');
  12954. * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
  12955. * var firstOrder = higherOrder.mergeAll(2);
  12956. * firstOrder.subscribe(x => console.log(x));
  12957. *
  12958. * @see {@link combineAll}
  12959. * @see {@link concatAll}
  12960. * @see {@link exhaust}
  12961. * @see {@link merge}
  12962. * @see {@link mergeMap}
  12963. * @see {@link mergeMapTo}
  12964. * @see {@link mergeScan}
  12965. * @see {@link switch}
  12966. * @see {@link zipAll}
  12967. *
  12968. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
  12969. * Observables being subscribed to concurrently.
  12970. * @return {Observable} An Observable that emits values coming from all the
  12971. * inner Observables emitted by the source Observable.
  12972. * @method mergeAll
  12973. * @owner Observable
  12974. */
  12975. function mergeAll$1(concurrent) {
  12976. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  12977. return mergeAll(concurrent)(this);
  12978. }
  12979. Observable.prototype.mergeAll = mergeAll$1;
  12980. /* tslint:enable:max-line-length */
  12981. /**
  12982. * Projects each source value to an Observable which is merged in the output
  12983. * Observable.
  12984. *
  12985. * <span class="informal">Maps each value to an Observable, then flattens all of
  12986. * these inner Observables using {@link mergeAll}.</span>
  12987. *
  12988. * <img src="./img/mergeMap.png" width="100%">
  12989. *
  12990. * Returns an Observable that emits items based on applying a function that you
  12991. * supply to each item emitted by the source Observable, where that function
  12992. * returns an Observable, and then merging those resulting Observables and
  12993. * emitting the results of this merger.
  12994. *
  12995. * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
  12996. * var letters = Rx.Observable.of('a', 'b', 'c');
  12997. * var result = letters.mergeMap(x =>
  12998. * Rx.Observable.interval(1000).map(i => x+i)
  12999. * );
  13000. * result.subscribe(x => console.log(x));
  13001. *
  13002. * // Results in the following:
  13003. * // a0
  13004. * // b0
  13005. * // c0
  13006. * // a1
  13007. * // b1
  13008. * // c1
  13009. * // continues to list a,b,c with respective ascending integers
  13010. *
  13011. * @see {@link concatMap}
  13012. * @see {@link exhaustMap}
  13013. * @see {@link merge}
  13014. * @see {@link mergeAll}
  13015. * @see {@link mergeMapTo}
  13016. * @see {@link mergeScan}
  13017. * @see {@link switchMap}
  13018. *
  13019. * @param {function(value: T, ?index: number): ObservableInput} project A function
  13020. * that, when applied to an item emitted by the source Observable, returns an
  13021. * Observable.
  13022. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  13023. * A function to produce the value on the output Observable based on the values
  13024. * and the indices of the source (outer) emission and the inner Observable
  13025. * emission. The arguments passed to this function are:
  13026. * - `outerValue`: the value that came from the source
  13027. * - `innerValue`: the value that came from the projected Observable
  13028. * - `outerIndex`: the "index" of the value that came from the source
  13029. * - `innerIndex`: the "index" of the value from the projected Observable
  13030. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  13031. * Observables being subscribed to concurrently.
  13032. * @return {Observable} An Observable that emits the result of applying the
  13033. * projection function (and the optional `resultSelector`) to each item emitted
  13034. * by the source Observable and merging the results of the Observables obtained
  13035. * from this transformation.
  13036. * @method mergeMap
  13037. * @owner Observable
  13038. */
  13039. function mergeMap$1(project, resultSelector, concurrent) {
  13040. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  13041. return mergeMap(project, resultSelector, concurrent)(this);
  13042. }
  13043. Observable.prototype.mergeMap = mergeMap$1;
  13044. Observable.prototype.flatMap = mergeMap$1;
  13045. /* tslint:enable:max-line-length */
  13046. /**
  13047. * Projects each source value to the same Observable which is merged multiple
  13048. * times in the output Observable.
  13049. *
  13050. * <span class="informal">It's like {@link mergeMap}, but maps each value always
  13051. * to the same inner Observable.</span>
  13052. *
  13053. * <img src="./img/mergeMapTo.png" width="100%">
  13054. *
  13055. * Maps each source value to the given Observable `innerObservable` regardless
  13056. * of the source value, and then merges those resulting Observables into one
  13057. * single Observable, which is the output Observable.
  13058. *
  13059. * @example <caption>For each click event, start an interval Observable ticking every 1 second</caption>
  13060. * var clicks = Rx.Observable.fromEvent(document, 'click');
  13061. * var result = clicks.mergeMapTo(Rx.Observable.interval(1000));
  13062. * result.subscribe(x => console.log(x));
  13063. *
  13064. * @see {@link concatMapTo}
  13065. * @see {@link merge}
  13066. * @see {@link mergeAll}
  13067. * @see {@link mergeMap}
  13068. * @see {@link mergeScan}
  13069. * @see {@link switchMapTo}
  13070. *
  13071. * @param {ObservableInput} innerObservable An Observable to replace each value from
  13072. * the source Observable.
  13073. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  13074. * A function to produce the value on the output Observable based on the values
  13075. * and the indices of the source (outer) emission and the inner Observable
  13076. * emission. The arguments passed to this function are:
  13077. * - `outerValue`: the value that came from the source
  13078. * - `innerValue`: the value that came from the projected Observable
  13079. * - `outerIndex`: the "index" of the value that came from the source
  13080. * - `innerIndex`: the "index" of the value from the projected Observable
  13081. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  13082. * Observables being subscribed to concurrently.
  13083. * @return {Observable} An Observable that emits items from the given
  13084. * `innerObservable` (and optionally transformed through `resultSelector`) every
  13085. * time a value is emitted on the source Observable.
  13086. * @method mergeMapTo
  13087. * @owner Observable
  13088. */
  13089. function mergeMapTo$1(innerObservable, resultSelector, concurrent) {
  13090. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  13091. if (typeof resultSelector === 'number') {
  13092. concurrent = resultSelector;
  13093. resultSelector = null;
  13094. }
  13095. return function (source) { return source.lift(new MergeMapToOperator(innerObservable, resultSelector, concurrent)); };
  13096. }
  13097. // TODO: Figure out correct signature here: an Operator<Observable<T>, R>
  13098. // needs to implement call(observer: Subscriber<R>): Subscriber<Observable<T>>
  13099. var MergeMapToOperator = (function () {
  13100. function MergeMapToOperator(ish, resultSelector, concurrent) {
  13101. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  13102. this.ish = ish;
  13103. this.resultSelector = resultSelector;
  13104. this.concurrent = concurrent;
  13105. }
  13106. MergeMapToOperator.prototype.call = function (observer, source) {
  13107. return source.subscribe(new MergeMapToSubscriber(observer, this.ish, this.resultSelector, this.concurrent));
  13108. };
  13109. return MergeMapToOperator;
  13110. }());
  13111. /**
  13112. * We need this JSDoc comment for affecting ESDoc.
  13113. * @ignore
  13114. * @extends {Ignored}
  13115. */
  13116. var MergeMapToSubscriber = (function (_super) {
  13117. __extends(MergeMapToSubscriber, _super);
  13118. function MergeMapToSubscriber(destination, ish, resultSelector, concurrent) {
  13119. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  13120. _super.call(this, destination);
  13121. this.ish = ish;
  13122. this.resultSelector = resultSelector;
  13123. this.concurrent = concurrent;
  13124. this.hasCompleted = false;
  13125. this.buffer = [];
  13126. this.active = 0;
  13127. this.index = 0;
  13128. }
  13129. MergeMapToSubscriber.prototype._next = function (value) {
  13130. if (this.active < this.concurrent) {
  13131. var resultSelector = this.resultSelector;
  13132. var index = this.index++;
  13133. var ish = this.ish;
  13134. var destination = this.destination;
  13135. this.active++;
  13136. this._innerSub(ish, destination, resultSelector, value, index);
  13137. }
  13138. else {
  13139. this.buffer.push(value);
  13140. }
  13141. };
  13142. MergeMapToSubscriber.prototype._innerSub = function (ish, destination, resultSelector, value, index) {
  13143. this.add(subscribeToResult(this, ish, value, index));
  13144. };
  13145. MergeMapToSubscriber.prototype._complete = function () {
  13146. this.hasCompleted = true;
  13147. if (this.active === 0 && this.buffer.length === 0) {
  13148. this.destination.complete();
  13149. }
  13150. };
  13151. MergeMapToSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  13152. var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
  13153. if (resultSelector) {
  13154. this.trySelectResult(outerValue, innerValue, outerIndex, innerIndex);
  13155. }
  13156. else {
  13157. destination.next(innerValue);
  13158. }
  13159. };
  13160. MergeMapToSubscriber.prototype.trySelectResult = function (outerValue, innerValue, outerIndex, innerIndex) {
  13161. var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
  13162. var result;
  13163. try {
  13164. result = resultSelector(outerValue, innerValue, outerIndex, innerIndex);
  13165. }
  13166. catch (err) {
  13167. destination.error(err);
  13168. return;
  13169. }
  13170. destination.next(result);
  13171. };
  13172. MergeMapToSubscriber.prototype.notifyError = function (err) {
  13173. this.destination.error(err);
  13174. };
  13175. MergeMapToSubscriber.prototype.notifyComplete = function (innerSub) {
  13176. var buffer = this.buffer;
  13177. this.remove(innerSub);
  13178. this.active--;
  13179. if (buffer.length > 0) {
  13180. this._next(buffer.shift());
  13181. }
  13182. else if (this.active === 0 && this.hasCompleted) {
  13183. this.destination.complete();
  13184. }
  13185. };
  13186. return MergeMapToSubscriber;
  13187. }(OuterSubscriber));
  13188. /* tslint:enable:max-line-length */
  13189. /**
  13190. * Projects each source value to the same Observable which is merged multiple
  13191. * times in the output Observable.
  13192. *
  13193. * <span class="informal">It's like {@link mergeMap}, but maps each value always
  13194. * to the same inner Observable.</span>
  13195. *
  13196. * <img src="./img/mergeMapTo.png" width="100%">
  13197. *
  13198. * Maps each source value to the given Observable `innerObservable` regardless
  13199. * of the source value, and then merges those resulting Observables into one
  13200. * single Observable, which is the output Observable.
  13201. *
  13202. * @example <caption>For each click event, start an interval Observable ticking every 1 second</caption>
  13203. * var clicks = Rx.Observable.fromEvent(document, 'click');
  13204. * var result = clicks.mergeMapTo(Rx.Observable.interval(1000));
  13205. * result.subscribe(x => console.log(x));
  13206. *
  13207. * @see {@link concatMapTo}
  13208. * @see {@link merge}
  13209. * @see {@link mergeAll}
  13210. * @see {@link mergeMap}
  13211. * @see {@link mergeScan}
  13212. * @see {@link switchMapTo}
  13213. *
  13214. * @param {ObservableInput} innerObservable An Observable to replace each value from
  13215. * the source Observable.
  13216. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  13217. * A function to produce the value on the output Observable based on the values
  13218. * and the indices of the source (outer) emission and the inner Observable
  13219. * emission. The arguments passed to this function are:
  13220. * - `outerValue`: the value that came from the source
  13221. * - `innerValue`: the value that came from the projected Observable
  13222. * - `outerIndex`: the "index" of the value that came from the source
  13223. * - `innerIndex`: the "index" of the value from the projected Observable
  13224. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  13225. * Observables being subscribed to concurrently.
  13226. * @return {Observable} An Observable that emits items from the given
  13227. * `innerObservable` (and optionally transformed through `resultSelector`) every
  13228. * time a value is emitted on the source Observable.
  13229. * @method mergeMapTo
  13230. * @owner Observable
  13231. */
  13232. function mergeMapTo$$1(innerObservable, resultSelector, concurrent) {
  13233. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  13234. return mergeMapTo$1(innerObservable, resultSelector, concurrent)(this);
  13235. }
  13236. Observable.prototype.flatMapTo = mergeMapTo$$1;
  13237. Observable.prototype.mergeMapTo = mergeMapTo$$1;
  13238. /**
  13239. * Applies an accumulator function over the source Observable where the
  13240. * accumulator function itself returns an Observable, then each intermediate
  13241. * Observable returned is merged into the output Observable.
  13242. *
  13243. * <span class="informal">It's like {@link scan}, but the Observables returned
  13244. * by the accumulator are merged into the outer Observable.</span>
  13245. *
  13246. * @example <caption>Count the number of click events</caption>
  13247. * const click$ = Rx.Observable.fromEvent(document, 'click');
  13248. * const one$ = click$.mapTo(1);
  13249. * const seed = 0;
  13250. * const count$ = one$.mergeScan((acc, one) => Rx.Observable.of(acc + one), seed);
  13251. * count$.subscribe(x => console.log(x));
  13252. *
  13253. * // Results:
  13254. * 1
  13255. * 2
  13256. * 3
  13257. * 4
  13258. * // ...and so on for each click
  13259. *
  13260. * @param {function(acc: R, value: T): Observable<R>} accumulator
  13261. * The accumulator function called on each source value.
  13262. * @param seed The initial accumulation value.
  13263. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of
  13264. * input Observables being subscribed to concurrently.
  13265. * @return {Observable<R>} An observable of the accumulated values.
  13266. * @method mergeScan
  13267. * @owner Observable
  13268. */
  13269. function mergeScan$1(accumulator, seed, concurrent) {
  13270. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  13271. return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); };
  13272. }
  13273. var MergeScanOperator = (function () {
  13274. function MergeScanOperator(accumulator, seed, concurrent) {
  13275. this.accumulator = accumulator;
  13276. this.seed = seed;
  13277. this.concurrent = concurrent;
  13278. }
  13279. MergeScanOperator.prototype.call = function (subscriber, source) {
  13280. return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent));
  13281. };
  13282. return MergeScanOperator;
  13283. }());
  13284. /**
  13285. * We need this JSDoc comment for affecting ESDoc.
  13286. * @ignore
  13287. * @extends {Ignored}
  13288. */
  13289. var MergeScanSubscriber = (function (_super) {
  13290. __extends(MergeScanSubscriber, _super);
  13291. function MergeScanSubscriber(destination, accumulator, acc, concurrent) {
  13292. _super.call(this, destination);
  13293. this.accumulator = accumulator;
  13294. this.acc = acc;
  13295. this.concurrent = concurrent;
  13296. this.hasValue = false;
  13297. this.hasCompleted = false;
  13298. this.buffer = [];
  13299. this.active = 0;
  13300. this.index = 0;
  13301. }
  13302. MergeScanSubscriber.prototype._next = function (value) {
  13303. if (this.active < this.concurrent) {
  13304. var index = this.index++;
  13305. var ish = tryCatch(this.accumulator)(this.acc, value);
  13306. var destination = this.destination;
  13307. if (ish === errorObject) {
  13308. destination.error(errorObject.e);
  13309. }
  13310. else {
  13311. this.active++;
  13312. this._innerSub(ish, value, index);
  13313. }
  13314. }
  13315. else {
  13316. this.buffer.push(value);
  13317. }
  13318. };
  13319. MergeScanSubscriber.prototype._innerSub = function (ish, value, index) {
  13320. this.add(subscribeToResult(this, ish, value, index));
  13321. };
  13322. MergeScanSubscriber.prototype._complete = function () {
  13323. this.hasCompleted = true;
  13324. if (this.active === 0 && this.buffer.length === 0) {
  13325. if (this.hasValue === false) {
  13326. this.destination.next(this.acc);
  13327. }
  13328. this.destination.complete();
  13329. }
  13330. };
  13331. MergeScanSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  13332. var destination = this.destination;
  13333. this.acc = innerValue;
  13334. this.hasValue = true;
  13335. destination.next(innerValue);
  13336. };
  13337. MergeScanSubscriber.prototype.notifyComplete = function (innerSub) {
  13338. var buffer = this.buffer;
  13339. this.remove(innerSub);
  13340. this.active--;
  13341. if (buffer.length > 0) {
  13342. this._next(buffer.shift());
  13343. }
  13344. else if (this.active === 0 && this.hasCompleted) {
  13345. if (this.hasValue === false) {
  13346. this.destination.next(this.acc);
  13347. }
  13348. this.destination.complete();
  13349. }
  13350. };
  13351. return MergeScanSubscriber;
  13352. }(OuterSubscriber));
  13353. /**
  13354. * Applies an accumulator function over the source Observable where the
  13355. * accumulator function itself returns an Observable, then each intermediate
  13356. * Observable returned is merged into the output Observable.
  13357. *
  13358. * <span class="informal">It's like {@link scan}, but the Observables returned
  13359. * by the accumulator are merged into the outer Observable.</span>
  13360. *
  13361. * @example <caption>Count the number of click events</caption>
  13362. * const click$ = Rx.Observable.fromEvent(document, 'click');
  13363. * const one$ = click$.mapTo(1);
  13364. * const seed = 0;
  13365. * const count$ = one$.mergeScan((acc, one) => Rx.Observable.of(acc + one), seed);
  13366. * count$.subscribe(x => console.log(x));
  13367. *
  13368. * // Results:
  13369. * 1
  13370. * 2
  13371. * 3
  13372. * 4
  13373. * // ...and so on for each click
  13374. *
  13375. * @param {function(acc: R, value: T): Observable<R>} accumulator
  13376. * The accumulator function called on each source value.
  13377. * @param seed The initial accumulation value.
  13378. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of
  13379. * input Observables being subscribed to concurrently.
  13380. * @return {Observable<R>} An observable of the accumulated values.
  13381. * @method mergeScan
  13382. * @owner Observable
  13383. */
  13384. function mergeScan$$1(accumulator, seed, concurrent) {
  13385. if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
  13386. return mergeScan$1(accumulator, seed, concurrent)(this);
  13387. }
  13388. Observable.prototype.mergeScan = mergeScan$$1;
  13389. /**
  13390. * The Min operator operates on an Observable that emits numbers (or items that can be compared with a provided function),
  13391. * and when source Observable completes it emits a single item: the item with the smallest value.
  13392. *
  13393. * <img src="./img/min.png" width="100%">
  13394. *
  13395. * @example <caption>Get the minimal value of a series of numbers</caption>
  13396. * Rx.Observable.of(5, 4, 7, 2, 8)
  13397. * .min()
  13398. * .subscribe(x => console.log(x)); // -> 2
  13399. *
  13400. * @example <caption>Use a comparer function to get the minimal item</caption>
  13401. * interface Person {
  13402. * age: number,
  13403. * name: string
  13404. * }
  13405. * Observable.of<Person>({age: 7, name: 'Foo'},
  13406. * {age: 5, name: 'Bar'},
  13407. * {age: 9, name: 'Beer'})
  13408. * .min<Person>( (a: Person, b: Person) => a.age < b.age ? -1 : 1)
  13409. * .subscribe((x: Person) => console.log(x.name)); // -> 'Bar'
  13410. * }
  13411. *
  13412. * @see {@link max}
  13413. *
  13414. * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the
  13415. * value of two items.
  13416. * @return {Observable<R>} An Observable that emits item with the smallest value.
  13417. * @method min
  13418. * @owner Observable
  13419. */
  13420. function min$1(comparer) {
  13421. var min = (typeof comparer === 'function')
  13422. ? function (x, y) { return comparer(x, y) < 0 ? x : y; }
  13423. : function (x, y) { return x < y ? x : y; };
  13424. return reduce(min);
  13425. }
  13426. /**
  13427. * The Min operator operates on an Observable that emits numbers (or items that can be compared with a provided function),
  13428. * and when source Observable completes it emits a single item: the item with the smallest value.
  13429. *
  13430. * <img src="./img/min.png" width="100%">
  13431. *
  13432. * @example <caption>Get the minimal value of a series of numbers</caption>
  13433. * Rx.Observable.of(5, 4, 7, 2, 8)
  13434. * .min()
  13435. * .subscribe(x => console.log(x)); // -> 2
  13436. *
  13437. * @example <caption>Use a comparer function to get the minimal item</caption>
  13438. * interface Person {
  13439. * age: number,
  13440. * name: string
  13441. * }
  13442. * Observable.of<Person>({age: 7, name: 'Foo'},
  13443. * {age: 5, name: 'Bar'},
  13444. * {age: 9, name: 'Beer'})
  13445. * .min<Person>( (a: Person, b: Person) => a.age < b.age ? -1 : 1)
  13446. * .subscribe((x: Person) => console.log(x.name)); // -> 'Bar'
  13447. * }
  13448. *
  13449. * @see {@link max}
  13450. *
  13451. * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the
  13452. * value of two items.
  13453. * @return {Observable<R>} An Observable that emits item with the smallest value.
  13454. * @method min
  13455. * @owner Observable
  13456. */
  13457. function min$$1(comparer) {
  13458. return min$1(comparer)(this);
  13459. }
  13460. Observable.prototype.min = min$$1;
  13461. function refCount() {
  13462. return function refCountOperatorFunction(source) {
  13463. return source.lift(new RefCountOperator$1(source));
  13464. };
  13465. }
  13466. var RefCountOperator$1 = (function () {
  13467. function RefCountOperator(connectable) {
  13468. this.connectable = connectable;
  13469. }
  13470. RefCountOperator.prototype.call = function (subscriber, source) {
  13471. var connectable = this.connectable;
  13472. connectable._refCount++;
  13473. var refCounter = new RefCountSubscriber$1(subscriber, connectable);
  13474. var subscription = source.subscribe(refCounter);
  13475. if (!refCounter.closed) {
  13476. refCounter.connection = connectable.connect();
  13477. }
  13478. return subscription;
  13479. };
  13480. return RefCountOperator;
  13481. }());
  13482. var RefCountSubscriber$1 = (function (_super) {
  13483. __extends(RefCountSubscriber, _super);
  13484. function RefCountSubscriber(destination, connectable) {
  13485. _super.call(this, destination);
  13486. this.connectable = connectable;
  13487. }
  13488. /** @deprecated internal use only */ RefCountSubscriber.prototype._unsubscribe = function () {
  13489. var connectable = this.connectable;
  13490. if (!connectable) {
  13491. this.connection = null;
  13492. return;
  13493. }
  13494. this.connectable = null;
  13495. var refCount = connectable._refCount;
  13496. if (refCount <= 0) {
  13497. this.connection = null;
  13498. return;
  13499. }
  13500. connectable._refCount = refCount - 1;
  13501. if (refCount > 1) {
  13502. this.connection = null;
  13503. return;
  13504. }
  13505. ///
  13506. // Compare the local RefCountSubscriber's connection Subscription to the
  13507. // connection Subscription on the shared ConnectableObservable. In cases
  13508. // where the ConnectableObservable source synchronously emits values, and
  13509. // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
  13510. // execution continues to here before the RefCountOperator has a chance to
  13511. // supply the RefCountSubscriber with the shared connection Subscription.
  13512. // For example:
  13513. // ```
  13514. // Observable.range(0, 10)
  13515. // .publish()
  13516. // .refCount()
  13517. // .take(5)
  13518. // .subscribe();
  13519. // ```
  13520. // In order to account for this case, RefCountSubscriber should only dispose
  13521. // the ConnectableObservable's shared connection Subscription if the
  13522. // connection Subscription exists, *and* either:
  13523. // a. RefCountSubscriber doesn't have a reference to the shared connection
  13524. // Subscription yet, or,
  13525. // b. RefCountSubscriber's connection Subscription reference is identical
  13526. // to the shared connection Subscription
  13527. ///
  13528. var connection = this.connection;
  13529. var sharedConnection = connectable._connection;
  13530. this.connection = null;
  13531. if (sharedConnection && (!connection || sharedConnection === connection)) {
  13532. sharedConnection.unsubscribe();
  13533. }
  13534. };
  13535. return RefCountSubscriber;
  13536. }(Subscriber));
  13537. /**
  13538. * @class ConnectableObservable<T>
  13539. */
  13540. var ConnectableObservable = (function (_super) {
  13541. __extends(ConnectableObservable, _super);
  13542. function ConnectableObservable(/** @deprecated internal use only */ source,
  13543. /** @deprecated internal use only */ subjectFactory) {
  13544. _super.call(this);
  13545. this.source = source;
  13546. this.subjectFactory = subjectFactory;
  13547. /** @deprecated internal use only */ this._refCount = 0;
  13548. this._isComplete = false;
  13549. }
  13550. /** @deprecated internal use only */ ConnectableObservable.prototype._subscribe = function (subscriber) {
  13551. return this.getSubject().subscribe(subscriber);
  13552. };
  13553. /** @deprecated internal use only */ ConnectableObservable.prototype.getSubject = function () {
  13554. var subject = this._subject;
  13555. if (!subject || subject.isStopped) {
  13556. this._subject = this.subjectFactory();
  13557. }
  13558. return this._subject;
  13559. };
  13560. ConnectableObservable.prototype.connect = function () {
  13561. var connection = this._connection;
  13562. if (!connection) {
  13563. this._isComplete = false;
  13564. connection = this._connection = new Subscription();
  13565. connection.add(this.source
  13566. .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
  13567. if (connection.closed) {
  13568. this._connection = null;
  13569. connection = Subscription.EMPTY;
  13570. }
  13571. else {
  13572. this._connection = connection;
  13573. }
  13574. }
  13575. return connection;
  13576. };
  13577. ConnectableObservable.prototype.refCount = function () {
  13578. return refCount()(this);
  13579. };
  13580. return ConnectableObservable;
  13581. }(Observable));
  13582. var connectableProto = ConnectableObservable.prototype;
  13583. var connectableObservableDescriptor = {
  13584. operator: { value: null },
  13585. _refCount: { value: 0, writable: true },
  13586. _subject: { value: null, writable: true },
  13587. _connection: { value: null, writable: true },
  13588. _subscribe: { value: connectableProto._subscribe },
  13589. _isComplete: { value: connectableProto._isComplete, writable: true },
  13590. getSubject: { value: connectableProto.getSubject },
  13591. connect: { value: connectableProto.connect },
  13592. refCount: { value: connectableProto.refCount }
  13593. };
  13594. var ConnectableSubscriber = (function (_super) {
  13595. __extends(ConnectableSubscriber, _super);
  13596. function ConnectableSubscriber(destination, connectable) {
  13597. _super.call(this, destination);
  13598. this.connectable = connectable;
  13599. }
  13600. ConnectableSubscriber.prototype._error = function (err) {
  13601. this._unsubscribe();
  13602. _super.prototype._error.call(this, err);
  13603. };
  13604. ConnectableSubscriber.prototype._complete = function () {
  13605. this.connectable._isComplete = true;
  13606. this._unsubscribe();
  13607. _super.prototype._complete.call(this);
  13608. };
  13609. /** @deprecated internal use only */ ConnectableSubscriber.prototype._unsubscribe = function () {
  13610. var connectable = this.connectable;
  13611. if (connectable) {
  13612. this.connectable = null;
  13613. var connection = connectable._connection;
  13614. connectable._refCount = 0;
  13615. connectable._subject = null;
  13616. connectable._connection = null;
  13617. if (connection) {
  13618. connection.unsubscribe();
  13619. }
  13620. }
  13621. };
  13622. return ConnectableSubscriber;
  13623. }(SubjectSubscriber));
  13624. var RefCountSubscriber = (function (_super) {
  13625. __extends(RefCountSubscriber, _super);
  13626. function RefCountSubscriber(destination, connectable) {
  13627. _super.call(this, destination);
  13628. this.connectable = connectable;
  13629. }
  13630. /** @deprecated internal use only */ RefCountSubscriber.prototype._unsubscribe = function () {
  13631. var connectable = this.connectable;
  13632. if (!connectable) {
  13633. this.connection = null;
  13634. return;
  13635. }
  13636. this.connectable = null;
  13637. var refCount$$1 = connectable._refCount;
  13638. if (refCount$$1 <= 0) {
  13639. this.connection = null;
  13640. return;
  13641. }
  13642. connectable._refCount = refCount$$1 - 1;
  13643. if (refCount$$1 > 1) {
  13644. this.connection = null;
  13645. return;
  13646. }
  13647. ///
  13648. // Compare the local RefCountSubscriber's connection Subscription to the
  13649. // connection Subscription on the shared ConnectableObservable. In cases
  13650. // where the ConnectableObservable source synchronously emits values, and
  13651. // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
  13652. // execution continues to here before the RefCountOperator has a chance to
  13653. // supply the RefCountSubscriber with the shared connection Subscription.
  13654. // For example:
  13655. // ```
  13656. // Observable.range(0, 10)
  13657. // .publish()
  13658. // .refCount()
  13659. // .take(5)
  13660. // .subscribe();
  13661. // ```
  13662. // In order to account for this case, RefCountSubscriber should only dispose
  13663. // the ConnectableObservable's shared connection Subscription if the
  13664. // connection Subscription exists, *and* either:
  13665. // a. RefCountSubscriber doesn't have a reference to the shared connection
  13666. // Subscription yet, or,
  13667. // b. RefCountSubscriber's connection Subscription reference is identical
  13668. // to the shared connection Subscription
  13669. ///
  13670. var connection = this.connection;
  13671. var sharedConnection = connectable._connection;
  13672. this.connection = null;
  13673. if (sharedConnection && (!connection || sharedConnection === connection)) {
  13674. sharedConnection.unsubscribe();
  13675. }
  13676. };
  13677. return RefCountSubscriber;
  13678. }(Subscriber));
  13679. /* tslint:enable:max-line-length */
  13680. /**
  13681. * Returns an Observable that emits the results of invoking a specified selector on items
  13682. * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
  13683. *
  13684. * <img src="./img/multicast.png" width="100%">
  13685. *
  13686. * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
  13687. * which the source sequence's elements will be multicast to the selector function
  13688. * or Subject to push source elements into.
  13689. * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
  13690. * as many times as needed, without causing multiple subscriptions to the source stream.
  13691. * Subscribers to the given source will receive all notifications of the source from the
  13692. * time of the subscription forward.
  13693. * @return {Observable} An Observable that emits the results of invoking the selector
  13694. * on the items emitted by a `ConnectableObservable` that shares a single subscription to
  13695. * the underlying stream.
  13696. * @method multicast
  13697. * @owner Observable
  13698. */
  13699. function multicast$1(subjectOrSubjectFactory, selector) {
  13700. return function multicastOperatorFunction(source) {
  13701. var subjectFactory;
  13702. if (typeof subjectOrSubjectFactory === 'function') {
  13703. subjectFactory = subjectOrSubjectFactory;
  13704. }
  13705. else {
  13706. subjectFactory = function subjectFactory() {
  13707. return subjectOrSubjectFactory;
  13708. };
  13709. }
  13710. if (typeof selector === 'function') {
  13711. return source.lift(new MulticastOperator(subjectFactory, selector));
  13712. }
  13713. var connectable = Object.create(source, connectableObservableDescriptor);
  13714. connectable.source = source;
  13715. connectable.subjectFactory = subjectFactory;
  13716. return connectable;
  13717. };
  13718. }
  13719. var MulticastOperator = (function () {
  13720. function MulticastOperator(subjectFactory, selector) {
  13721. this.subjectFactory = subjectFactory;
  13722. this.selector = selector;
  13723. }
  13724. MulticastOperator.prototype.call = function (subscriber, source) {
  13725. var selector = this.selector;
  13726. var subject = this.subjectFactory();
  13727. var subscription = selector(subject).subscribe(subscriber);
  13728. subscription.add(source.subscribe(subject));
  13729. return subscription;
  13730. };
  13731. return MulticastOperator;
  13732. }());
  13733. /* tslint:enable:max-line-length */
  13734. /**
  13735. * Allows source Observable to be subscribed only once with a Subject of choice,
  13736. * while still sharing its values between multiple subscribers.
  13737. *
  13738. * <span class="informal">Subscribe to Observable once, but send its values to multiple subscribers.</span>
  13739. *
  13740. * <img src="./img/multicast.png" width="100%">
  13741. *
  13742. * `multicast` is an operator that works in two modes.
  13743. *
  13744. * In the first mode you provide a single argument to it, which can be either an initialized Subject or a Subject
  13745. * factory. As a result you will get a special kind of an Observable - a {@link ConnectableObservable}. It can be
  13746. * subscribed multiple times, just as regular Observable, but it won't subscribe to the source Observable at that
  13747. * moment. It will do it only if you call its `connect` method. This means you can essentially control by hand, when
  13748. * source Observable will be actually subscribed. What is more, ConnectableObservable will share this one subscription
  13749. * between all of its subscribers. This means that, for example, `ajax` Observable will only send a request once,
  13750. * even though usually it would send a request per every subscriber. Since it sends a request at the moment of
  13751. * subscription, here request would be sent when the `connect` method of a ConnectableObservable is called.
  13752. *
  13753. * The most common pattern of using ConnectableObservable is calling `connect` when the first consumer subscribes,
  13754. * keeping the subscription alive while several consumers come and go and finally unsubscribing from the source
  13755. * Observable, when the last consumer unsubscribes. To not implement that logic over and over again,
  13756. * ConnectableObservable has a special operator, `refCount`. When called, it returns an Observable, which will count
  13757. * the number of consumers subscribed to it and keep ConnectableObservable connected as long as there is at least
  13758. * one consumer. So if you don't actually need to decide yourself when to connect and disconnect a
  13759. * ConnectableObservable, use `refCount`.
  13760. *
  13761. * The second mode is invoked by calling `multicast` with an additional, second argument - selector function.
  13762. * This function accepts an Observable - which basically mirrors the source Observable - and returns Observable
  13763. * as well, which should be the input stream modified by any operators you want. Note that in this
  13764. * mode you cannot provide initialized Subject as a first argument - it has to be a Subject factory. If
  13765. * you provide selector function, `multicast` returns just a regular Observable, instead of ConnectableObservable.
  13766. * Thus, as usual, each subscription to this stream triggers subscription to the source Observable. However,
  13767. * if inside the selector function you subscribe to the input Observable multiple times, actual source stream
  13768. * will be subscribed only once. So if you have a chain of operators that use some Observable many times,
  13769. * but you want to subscribe to that Observable only once, this is the mode you would use.
  13770. *
  13771. * Subject provided as a first parameter of `multicast` is used as a proxy for the single subscription to the
  13772. * source Observable. It means that all values from the source stream go through that Subject. Thus, if a Subject
  13773. * has some special properties, Observable returned by `multicast` will have them as well. If you want to use
  13774. * `multicast` with a Subject that is one of the ones included in RxJS by default - {@link Subject},
  13775. * {@link AsyncSubject}, {@link BehaviorSubject}, or {@link ReplaySubject} - simply use {@link publish},
  13776. * {@link publishLast}, {@link publishBehavior} or {@link publishReplay} respectively. These are actually
  13777. * just wrappers around `multicast`, with a specific Subject hardcoded inside.
  13778. *
  13779. * Also, if you use {@link publish} or {@link publishReplay} with a ConnectableObservables `refCount` operator,
  13780. * you can simply use {@link share} and {@link shareReplay} respectively, which chain these two.
  13781. *
  13782. * @example <caption>Use ConnectableObservable</caption>
  13783. * const seconds = Rx.Observable.interval(1000);
  13784. * const connectableSeconds = seconds.multicast(new Subject());
  13785. *
  13786. * connectableSeconds.subscribe(value => console.log('first: ' + value));
  13787. * connectableSeconds.subscribe(value => console.log('second: ' + value));
  13788. *
  13789. * // At this point still nothing happens, even though we subscribed twice.
  13790. *
  13791. * connectableSeconds.connect();
  13792. *
  13793. * // From now on `seconds` are being logged to the console,
  13794. * // twice per every second. `seconds` Observable was however only subscribed once,
  13795. * // so under the hood Observable.interval had only one clock started.
  13796. *
  13797. * @example <caption>Use selector</caption>
  13798. * const seconds = Rx.Observable.interval(1000);
  13799. *
  13800. * seconds
  13801. * .multicast(
  13802. * () => new Subject(),
  13803. * seconds => seconds.zip(seconds) // Usually zip would subscribe to `seconds` twice.
  13804. * // Because we are inside selector, `seconds` is subscribed once,
  13805. * ) // thus starting only one clock used internally by Observable.interval.
  13806. * .subscribe();
  13807. *
  13808. * @see {@link publish}
  13809. * @see {@link publishLast}
  13810. * @see {@link publishBehavior}
  13811. * @see {@link publishReplay}
  13812. * @see {@link share}
  13813. * @see {@link shareReplay}
  13814. *
  13815. * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate Subject through
  13816. * which the source sequence's elements will be multicast to the selector function input Observable or
  13817. * ConnectableObservable returned by the operator.
  13818. * @param {Function} [selector] - Optional selector function that can use the input stream
  13819. * as many times as needed, without causing multiple subscriptions to the source stream.
  13820. * Subscribers to the input source will receive all notifications of the source from the
  13821. * time of the subscription forward.
  13822. * @return {Observable<T>|ConnectableObservable<T>} An Observable that emits the results of invoking the selector
  13823. * on the source stream or a special {@link ConnectableObservable}, if selector was not provided.
  13824. *
  13825. * @method multicast
  13826. * @owner Observable
  13827. */
  13828. function multicast$$1(subjectOrSubjectFactory, selector) {
  13829. return multicast$1(subjectOrSubjectFactory, selector)(this);
  13830. }
  13831. Observable.prototype.multicast = multicast$$1;
  13832. /**
  13833. *
  13834. * Re-emits all notifications from source Observable with specified scheduler.
  13835. *
  13836. * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
  13837. *
  13838. * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
  13839. * notifications emitted by the source Observable. It might be useful, if you do not have control over
  13840. * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
  13841. *
  13842. * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
  13843. * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
  13844. * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
  13845. * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
  13846. * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
  13847. * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
  13848. * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
  13849. * little bit more, to ensure that they are emitted at expected moments.
  13850. *
  13851. * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
  13852. * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
  13853. * will delay all notifications - including error notifications - while `delay` will pass through error
  13854. * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
  13855. * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
  13856. * for notification emissions in general.
  13857. *
  13858. * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
  13859. * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
  13860. * // with async scheduler by default...
  13861. *
  13862. * intervals
  13863. * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame
  13864. * .subscribe(val => { // scheduler to ensure smooth animation.
  13865. * someDiv.style.height = val + 'px';
  13866. * });
  13867. *
  13868. * @see {@link delay}
  13869. *
  13870. * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
  13871. * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
  13872. * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
  13873. * but with provided scheduler.
  13874. *
  13875. * @method observeOn
  13876. * @owner Observable
  13877. */
  13878. function observeOn$1(scheduler, delay) {
  13879. if (delay === void 0) { delay = 0; }
  13880. return observeOn(scheduler, delay)(this);
  13881. }
  13882. Observable.prototype.observeOn = observeOn$1;
  13883. /* tslint:enable:max-line-length */
  13884. /**
  13885. * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one
  13886. * that was passed.
  13887. *
  13888. * <span class="informal">Execute series of Observables no matter what, even if it means swallowing errors.</span>
  13889. *
  13890. * <img src="./img/onErrorResumeNext.png" width="100%">
  13891. *
  13892. * `onErrorResumeNext` is an operator that accepts a series of Observables, provided either directly as
  13893. * arguments or as an array. If no single Observable is provided, returned Observable will simply behave the same
  13894. * as the source.
  13895. *
  13896. * `onErrorResumeNext` returns an Observable that starts by subscribing and re-emitting values from the source Observable.
  13897. * When its stream of values ends - no matter if Observable completed or emitted an error - `onErrorResumeNext`
  13898. * will subscribe to the first Observable that was passed as an argument to the method. It will start re-emitting
  13899. * its values as well and - again - when that stream ends, `onErrorResumeNext` will proceed to subscribing yet another
  13900. * Observable in provided series, no matter if previous Observable completed or ended with an error. This will
  13901. * be happening until there is no more Observables left in the series, at which point returned Observable will
  13902. * complete - even if the last subscribed stream ended with an error.
  13903. *
  13904. * `onErrorResumeNext` can be therefore thought of as version of {@link concat} operator, which is more permissive
  13905. * when it comes to the errors emitted by its input Observables. While `concat` subscribes to the next Observable
  13906. * in series only if previous one successfully completed, `onErrorResumeNext` subscribes even if it ended with
  13907. * an error.
  13908. *
  13909. * Note that you do not get any access to errors emitted by the Observables. In particular do not
  13910. * expect these errors to appear in error callback passed to {@link subscribe}. If you want to take
  13911. * specific actions based on what error was emitted by an Observable, you should try out {@link catch} instead.
  13912. *
  13913. *
  13914. * @example <caption>Subscribe to the next Observable after map fails</caption>
  13915. * Rx.Observable.of(1, 2, 3, 0)
  13916. * .map(x => {
  13917. * if (x === 0) { throw Error(); }
  13918. return 10 / x;
  13919. * })
  13920. * .onErrorResumeNext(Rx.Observable.of(1, 2, 3))
  13921. * .subscribe(
  13922. * val => console.log(val),
  13923. * err => console.log(err), // Will never be called.
  13924. * () => console.log('that\'s it!')
  13925. * );
  13926. *
  13927. * // Logs:
  13928. * // 10
  13929. * // 5
  13930. * // 3.3333333333333335
  13931. * // 1
  13932. * // 2
  13933. * // 3
  13934. * // "that's it!"
  13935. *
  13936. * @see {@link concat}
  13937. * @see {@link catch}
  13938. *
  13939. * @param {...ObservableInput} observables Observables passed either directly or as an array.
  13940. * @return {Observable} An Observable that emits values from source Observable, but - if it errors - subscribes
  13941. * to the next passed Observable and so on, until it completes or runs out of Observables.
  13942. * @method onErrorResumeNext
  13943. * @owner Observable
  13944. */
  13945. function onErrorResumeNext$2() {
  13946. var nextSources = [];
  13947. for (var _i = 0; _i < arguments.length; _i++) {
  13948. nextSources[_i - 0] = arguments[_i];
  13949. }
  13950. return onErrorResumeNext$1.apply(void 0, nextSources)(this);
  13951. }
  13952. Observable.prototype.onErrorResumeNext = onErrorResumeNext$2;
  13953. /**
  13954. * Groups pairs of consecutive emissions together and emits them as an array of
  13955. * two values.
  13956. *
  13957. * <span class="informal">Puts the current value and previous value together as
  13958. * an array, and emits that.</span>
  13959. *
  13960. * <img src="./img/pairwise.png" width="100%">
  13961. *
  13962. * The Nth emission from the source Observable will cause the output Observable
  13963. * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
  13964. * pair. For this reason, `pairwise` emits on the second and subsequent
  13965. * emissions from the source Observable, but not on the first emission, because
  13966. * there is no previous value in that case.
  13967. *
  13968. * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
  13969. * var clicks = Rx.Observable.fromEvent(document, 'click');
  13970. * var pairs = clicks.pairwise();
  13971. * var distance = pairs.map(pair => {
  13972. * var x0 = pair[0].clientX;
  13973. * var y0 = pair[0].clientY;
  13974. * var x1 = pair[1].clientX;
  13975. * var y1 = pair[1].clientY;
  13976. * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
  13977. * });
  13978. * distance.subscribe(x => console.log(x));
  13979. *
  13980. * @see {@link buffer}
  13981. * @see {@link bufferCount}
  13982. *
  13983. * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
  13984. * consecutive values from the source Observable.
  13985. * @method pairwise
  13986. * @owner Observable
  13987. */
  13988. function pairwise$1() {
  13989. return function (source) { return source.lift(new PairwiseOperator()); };
  13990. }
  13991. var PairwiseOperator = (function () {
  13992. function PairwiseOperator() {
  13993. }
  13994. PairwiseOperator.prototype.call = function (subscriber, source) {
  13995. return source.subscribe(new PairwiseSubscriber(subscriber));
  13996. };
  13997. return PairwiseOperator;
  13998. }());
  13999. /**
  14000. * We need this JSDoc comment for affecting ESDoc.
  14001. * @ignore
  14002. * @extends {Ignored}
  14003. */
  14004. var PairwiseSubscriber = (function (_super) {
  14005. __extends(PairwiseSubscriber, _super);
  14006. function PairwiseSubscriber(destination) {
  14007. _super.call(this, destination);
  14008. this.hasPrev = false;
  14009. }
  14010. PairwiseSubscriber.prototype._next = function (value) {
  14011. if (this.hasPrev) {
  14012. this.destination.next([this.prev, value]);
  14013. }
  14014. else {
  14015. this.hasPrev = true;
  14016. }
  14017. this.prev = value;
  14018. };
  14019. return PairwiseSubscriber;
  14020. }(Subscriber));
  14021. /**
  14022. * Groups pairs of consecutive emissions together and emits them as an array of
  14023. * two values.
  14024. *
  14025. * <span class="informal">Puts the current value and previous value together as
  14026. * an array, and emits that.</span>
  14027. *
  14028. * <img src="./img/pairwise.png" width="100%">
  14029. *
  14030. * The Nth emission from the source Observable will cause the output Observable
  14031. * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
  14032. * pair. For this reason, `pairwise` emits on the second and subsequent
  14033. * emissions from the source Observable, but not on the first emission, because
  14034. * there is no previous value in that case.
  14035. *
  14036. * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
  14037. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14038. * var pairs = clicks.pairwise();
  14039. * var distance = pairs.map(pair => {
  14040. * var x0 = pair[0].clientX;
  14041. * var y0 = pair[0].clientY;
  14042. * var x1 = pair[1].clientX;
  14043. * var y1 = pair[1].clientY;
  14044. * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
  14045. * });
  14046. * distance.subscribe(x => console.log(x));
  14047. *
  14048. * @see {@link buffer}
  14049. * @see {@link bufferCount}
  14050. *
  14051. * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
  14052. * consecutive values from the source Observable.
  14053. * @method pairwise
  14054. * @owner Observable
  14055. */
  14056. function pairwise$$1() {
  14057. return pairwise$1()(this);
  14058. }
  14059. Observable.prototype.pairwise = pairwise$$1;
  14060. function not(pred, thisArg) {
  14061. function notPred() {
  14062. return !(notPred.pred.apply(notPred.thisArg, arguments));
  14063. }
  14064. notPred.pred = pred;
  14065. notPred.thisArg = thisArg;
  14066. return notPred;
  14067. }
  14068. /**
  14069. * Splits the source Observable into two, one with values that satisfy a
  14070. * predicate, and another with values that don't satisfy the predicate.
  14071. *
  14072. * <span class="informal">It's like {@link filter}, but returns two Observables:
  14073. * one like the output of {@link filter}, and the other with values that did not
  14074. * pass the condition.</span>
  14075. *
  14076. * <img src="./img/partition.png" width="100%">
  14077. *
  14078. * `partition` outputs an array with two Observables that partition the values
  14079. * from the source Observable through the given `predicate` function. The first
  14080. * Observable in that array emits source values for which the predicate argument
  14081. * returns true. The second Observable emits source values for which the
  14082. * predicate returns false. The first behaves like {@link filter} and the second
  14083. * behaves like {@link filter} with the predicate negated.
  14084. *
  14085. * @example <caption>Partition click events into those on DIV elements and those elsewhere</caption>
  14086. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14087. * var parts = clicks.partition(ev => ev.target.tagName === 'DIV');
  14088. * var clicksOnDivs = parts[0];
  14089. * var clicksElsewhere = parts[1];
  14090. * clicksOnDivs.subscribe(x => console.log('DIV clicked: ', x));
  14091. * clicksElsewhere.subscribe(x => console.log('Other clicked: ', x));
  14092. *
  14093. * @see {@link filter}
  14094. *
  14095. * @param {function(value: T, index: number): boolean} predicate A function that
  14096. * evaluates each value emitted by the source Observable. If it returns `true`,
  14097. * the value is emitted on the first Observable in the returned array, if
  14098. * `false` the value is emitted on the second Observable in the array. The
  14099. * `index` parameter is the number `i` for the i-th source emission that has
  14100. * happened since the subscription, starting from the number `0`.
  14101. * @param {any} [thisArg] An optional argument to determine the value of `this`
  14102. * in the `predicate` function.
  14103. * @return {[Observable<T>, Observable<T>]} An array with two Observables: one
  14104. * with values that passed the predicate, and another with values that did not
  14105. * pass the predicate.
  14106. * @method partition
  14107. * @owner Observable
  14108. */
  14109. function partition$1(predicate, thisArg) {
  14110. return function (source) { return [
  14111. filter$1(predicate, thisArg)(source),
  14112. filter$1(not(predicate, thisArg))(source)
  14113. ]; };
  14114. }
  14115. /**
  14116. * Splits the source Observable into two, one with values that satisfy a
  14117. * predicate, and another with values that don't satisfy the predicate.
  14118. *
  14119. * <span class="informal">It's like {@link filter}, but returns two Observables:
  14120. * one like the output of {@link filter}, and the other with values that did not
  14121. * pass the condition.</span>
  14122. *
  14123. * <img src="./img/partition.png" width="100%">
  14124. *
  14125. * `partition` outputs an array with two Observables that partition the values
  14126. * from the source Observable through the given `predicate` function. The first
  14127. * Observable in that array emits source values for which the predicate argument
  14128. * returns true. The second Observable emits source values for which the
  14129. * predicate returns false. The first behaves like {@link filter} and the second
  14130. * behaves like {@link filter} with the predicate negated.
  14131. *
  14132. * @example <caption>Partition click events into those on DIV elements and those elsewhere</caption>
  14133. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14134. * var parts = clicks.partition(ev => ev.target.tagName === 'DIV');
  14135. * var clicksOnDivs = parts[0];
  14136. * var clicksElsewhere = parts[1];
  14137. * clicksOnDivs.subscribe(x => console.log('DIV clicked: ', x));
  14138. * clicksElsewhere.subscribe(x => console.log('Other clicked: ', x));
  14139. *
  14140. * @see {@link filter}
  14141. *
  14142. * @param {function(value: T, index: number): boolean} predicate A function that
  14143. * evaluates each value emitted by the source Observable. If it returns `true`,
  14144. * the value is emitted on the first Observable in the returned array, if
  14145. * `false` the value is emitted on the second Observable in the array. The
  14146. * `index` parameter is the number `i` for the i-th source emission that has
  14147. * happened since the subscription, starting from the number `0`.
  14148. * @param {any} [thisArg] An optional argument to determine the value of `this`
  14149. * in the `predicate` function.
  14150. * @return {[Observable<T>, Observable<T>]} An array with two Observables: one
  14151. * with values that passed the predicate, and another with values that did not
  14152. * pass the predicate.
  14153. * @method partition
  14154. * @owner Observable
  14155. */
  14156. function partition$$1(predicate, thisArg) {
  14157. return partition$1(predicate, thisArg)(this);
  14158. }
  14159. Observable.prototype.partition = partition$$1;
  14160. /**
  14161. * Maps each source value (an object) to its specified nested property.
  14162. *
  14163. * <span class="informal">Like {@link map}, but meant only for picking one of
  14164. * the nested properties of every emitted object.</span>
  14165. *
  14166. * <img src="./img/pluck.png" width="100%">
  14167. *
  14168. * Given a list of strings describing a path to an object property, retrieves
  14169. * the value of a specified nested property from all values in the source
  14170. * Observable. If a property can't be resolved, it will return `undefined` for
  14171. * that value.
  14172. *
  14173. * @example <caption>Map every click to the tagName of the clicked target element</caption>
  14174. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14175. * var tagNames = clicks.pluck('target', 'tagName');
  14176. * tagNames.subscribe(x => console.log(x));
  14177. *
  14178. * @see {@link map}
  14179. *
  14180. * @param {...string} properties The nested properties to pluck from each source
  14181. * value (an object).
  14182. * @return {Observable} A new Observable of property values from the source values.
  14183. * @method pluck
  14184. * @owner Observable
  14185. */
  14186. function pluck$1() {
  14187. var properties = [];
  14188. for (var _i = 0; _i < arguments.length; _i++) {
  14189. properties[_i - 0] = arguments[_i];
  14190. }
  14191. var length = properties.length;
  14192. if (length === 0) {
  14193. throw new Error('list of properties cannot be empty.');
  14194. }
  14195. return function (source) { return map(plucker(properties, length))(source); };
  14196. }
  14197. function plucker(props, length) {
  14198. var mapper = function (x) {
  14199. var currentProp = x;
  14200. for (var i = 0; i < length; i++) {
  14201. var p = currentProp[props[i]];
  14202. if (typeof p !== 'undefined') {
  14203. currentProp = p;
  14204. }
  14205. else {
  14206. return undefined;
  14207. }
  14208. }
  14209. return currentProp;
  14210. };
  14211. return mapper;
  14212. }
  14213. /**
  14214. * Maps each source value (an object) to its specified nested property.
  14215. *
  14216. * <span class="informal">Like {@link map}, but meant only for picking one of
  14217. * the nested properties of every emitted object.</span>
  14218. *
  14219. * <img src="./img/pluck.png" width="100%">
  14220. *
  14221. * Given a list of strings describing a path to an object property, retrieves
  14222. * the value of a specified nested property from all values in the source
  14223. * Observable. If a property can't be resolved, it will return `undefined` for
  14224. * that value.
  14225. *
  14226. * @example <caption>Map every click to the tagName of the clicked target element</caption>
  14227. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14228. * var tagNames = clicks.pluck('target', 'tagName');
  14229. * tagNames.subscribe(x => console.log(x));
  14230. *
  14231. * @see {@link map}
  14232. *
  14233. * @param {...string} properties The nested properties to pluck from each source
  14234. * value (an object).
  14235. * @return {Observable} A new Observable of property values from the source values.
  14236. * @method pluck
  14237. * @owner Observable
  14238. */
  14239. function pluck$$1() {
  14240. var properties = [];
  14241. for (var _i = 0; _i < arguments.length; _i++) {
  14242. properties[_i - 0] = arguments[_i];
  14243. }
  14244. return pluck$1.apply(void 0, properties)(this);
  14245. }
  14246. Observable.prototype.pluck = pluck$$1;
  14247. /* tslint:enable:max-line-length */
  14248. /**
  14249. * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
  14250. * before it begins emitting items to those Observers that have subscribed to it.
  14251. *
  14252. * <img src="./img/publish.png" width="100%">
  14253. *
  14254. * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
  14255. * as needed, without causing multiple subscriptions to the source sequence.
  14256. * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
  14257. * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
  14258. * @method publish
  14259. * @owner Observable
  14260. */
  14261. function publish$1(selector) {
  14262. return selector ?
  14263. multicast$1(function () { return new Subject(); }, selector) :
  14264. multicast$1(new Subject());
  14265. }
  14266. /* tslint:enable:max-line-length */
  14267. /**
  14268. * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
  14269. * before it begins emitting items to those Observers that have subscribed to it.
  14270. *
  14271. * <img src="./img/publish.png" width="100%">
  14272. *
  14273. * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
  14274. * as needed, without causing multiple subscriptions to the source sequence.
  14275. * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
  14276. * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
  14277. * @method publish
  14278. * @owner Observable
  14279. */
  14280. function publish$$1(selector) {
  14281. return publish$1(selector)(this);
  14282. }
  14283. Observable.prototype.publish = publish$$1;
  14284. /**
  14285. * @class BehaviorSubject<T>
  14286. */
  14287. var BehaviorSubject = (function (_super) {
  14288. __extends(BehaviorSubject, _super);
  14289. function BehaviorSubject(_value) {
  14290. _super.call(this);
  14291. this._value = _value;
  14292. }
  14293. Object.defineProperty(BehaviorSubject.prototype, "value", {
  14294. get: function () {
  14295. return this.getValue();
  14296. },
  14297. enumerable: true,
  14298. configurable: true
  14299. });
  14300. /** @deprecated internal use only */ BehaviorSubject.prototype._subscribe = function (subscriber) {
  14301. var subscription = _super.prototype._subscribe.call(this, subscriber);
  14302. if (subscription && !subscription.closed) {
  14303. subscriber.next(this._value);
  14304. }
  14305. return subscription;
  14306. };
  14307. BehaviorSubject.prototype.getValue = function () {
  14308. if (this.hasError) {
  14309. throw this.thrownError;
  14310. }
  14311. else if (this.closed) {
  14312. throw new ObjectUnsubscribedError();
  14313. }
  14314. else {
  14315. return this._value;
  14316. }
  14317. };
  14318. BehaviorSubject.prototype.next = function (value) {
  14319. _super.prototype.next.call(this, this._value = value);
  14320. };
  14321. return BehaviorSubject;
  14322. }(Subject));
  14323. /**
  14324. * @param value
  14325. * @return {ConnectableObservable<T>}
  14326. * @method publishBehavior
  14327. * @owner Observable
  14328. */
  14329. function publishBehavior$1(value) {
  14330. return function (source) { return multicast$1(new BehaviorSubject(value))(source); };
  14331. }
  14332. /**
  14333. * @param value
  14334. * @return {ConnectableObservable<T>}
  14335. * @method publishBehavior
  14336. * @owner Observable
  14337. */
  14338. function publishBehavior$$1(value) {
  14339. return publishBehavior$1(value)(this);
  14340. }
  14341. Observable.prototype.publishBehavior = publishBehavior$$1;
  14342. /* tslint:enable:max-line-length */
  14343. function publishReplay$1(bufferSize, windowTime, selectorOrScheduler, scheduler) {
  14344. if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
  14345. scheduler = selectorOrScheduler;
  14346. }
  14347. var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
  14348. var subject = new ReplaySubject(bufferSize, windowTime, scheduler);
  14349. return function (source) { return multicast$1(function () { return subject; }, selector)(source); };
  14350. }
  14351. /* tslint:enable:max-line-length */
  14352. /**
  14353. * @param bufferSize
  14354. * @param windowTime
  14355. * @param selectorOrScheduler
  14356. * @param scheduler
  14357. * @return {Observable<T> | ConnectableObservable<T>}
  14358. * @method publishReplay
  14359. * @owner Observable
  14360. */
  14361. function publishReplay$$1(bufferSize, windowTime, selectorOrScheduler, scheduler) {
  14362. return publishReplay$1(bufferSize, windowTime, selectorOrScheduler, scheduler)(this);
  14363. }
  14364. Observable.prototype.publishReplay = publishReplay$$1;
  14365. function publishLast$1() {
  14366. return function (source) { return multicast$1(new AsyncSubject())(source); };
  14367. }
  14368. /**
  14369. * @return {ConnectableObservable<T>}
  14370. * @method publishLast
  14371. * @owner Observable
  14372. */
  14373. function publishLast$$1() {
  14374. //TODO(benlesh): correct type-flow through here.
  14375. return publishLast$1()(this);
  14376. }
  14377. Observable.prototype.publishLast = publishLast$$1;
  14378. /* tslint:enable:max-line-length */
  14379. /**
  14380. * Returns an Observable that mirrors the first source Observable to emit an item
  14381. * from the combination of this Observable and supplied Observables.
  14382. * @param {...Observables} ...observables Sources used to race for which Observable emits first.
  14383. * @return {Observable} An Observable that mirrors the output of the first Observable to emit an item.
  14384. * @method race
  14385. * @owner Observable
  14386. */
  14387. function race$2() {
  14388. var observables = [];
  14389. for (var _i = 0; _i < arguments.length; _i++) {
  14390. observables[_i - 0] = arguments[_i];
  14391. }
  14392. return function raceOperatorFunction(source) {
  14393. // if the only argument is an array, it was most likely called with
  14394. // `pair([obs1, obs2, ...])`
  14395. if (observables.length === 1 && isArray(observables[0])) {
  14396. observables = observables[0];
  14397. }
  14398. return source.lift.call(race.apply(void 0, [source].concat(observables)));
  14399. };
  14400. }
  14401. /* tslint:enable:max-line-length */
  14402. /**
  14403. * Returns an Observable that mirrors the first source Observable to emit an item
  14404. * from the combination of this Observable and supplied Observables.
  14405. * @param {...Observables} ...observables Sources used to race for which Observable emits first.
  14406. * @return {Observable} An Observable that mirrors the output of the first Observable to emit an item.
  14407. * @method race
  14408. * @owner Observable
  14409. */
  14410. function race$1() {
  14411. var observables = [];
  14412. for (var _i = 0; _i < arguments.length; _i++) {
  14413. observables[_i - 0] = arguments[_i];
  14414. }
  14415. return race$2.apply(void 0, observables)(this);
  14416. }
  14417. Observable.prototype.race = race$1;
  14418. /* tslint:enable:max-line-length */
  14419. /**
  14420. * Applies an accumulator function over the source Observable, and returns the
  14421. * accumulated result when the source completes, given an optional seed value.
  14422. *
  14423. * <span class="informal">Combines together all values emitted on the source,
  14424. * using an accumulator function that knows how to join a new source value into
  14425. * the accumulation from the past.</span>
  14426. *
  14427. * <img src="./img/reduce.png" width="100%">
  14428. *
  14429. * Like
  14430. * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
  14431. * `reduce` applies an `accumulator` function against an accumulation and each
  14432. * value of the source Observable (from the past) to reduce it to a single
  14433. * value, emitted on the output Observable. Note that `reduce` will only emit
  14434. * one value, only when the source Observable completes. It is equivalent to
  14435. * applying operator {@link scan} followed by operator {@link last}.
  14436. *
  14437. * Returns an Observable that applies a specified `accumulator` function to each
  14438. * item emitted by the source Observable. If a `seed` value is specified, then
  14439. * that value will be used as the initial value for the accumulator. If no seed
  14440. * value is specified, the first item of the source is used as the seed.
  14441. *
  14442. * @example <caption>Count the number of click events that happened in 5 seconds</caption>
  14443. * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click')
  14444. * .takeUntil(Rx.Observable.interval(5000));
  14445. * var ones = clicksInFiveSeconds.mapTo(1);
  14446. * var seed = 0;
  14447. * var count = ones.reduce((acc, one) => acc + one, seed);
  14448. * count.subscribe(x => console.log(x));
  14449. *
  14450. * @see {@link count}
  14451. * @see {@link expand}
  14452. * @see {@link mergeScan}
  14453. * @see {@link scan}
  14454. *
  14455. * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function
  14456. * called on each source value.
  14457. * @param {R} [seed] The initial accumulation value.
  14458. * @return {Observable<R>} An Observable that emits a single value that is the
  14459. * result of accumulating the values emitted by the source Observable.
  14460. * @method reduce
  14461. * @owner Observable
  14462. */
  14463. function reduce$1(accumulator, seed) {
  14464. // providing a seed of `undefined` *should* be valid and trigger
  14465. // hasSeed! so don't use `seed !== undefined` checks!
  14466. // For this reason, we have to check it here at the original call site
  14467. // otherwise inside Operator/Subscriber we won't know if `undefined`
  14468. // means they didn't provide anything or if they literally provided `undefined`
  14469. if (arguments.length >= 2) {
  14470. return reduce(accumulator, seed)(this);
  14471. }
  14472. return reduce(accumulator)(this);
  14473. }
  14474. Observable.prototype.reduce = reduce$1;
  14475. /**
  14476. * Returns an Observable that repeats the stream of items emitted by the source Observable at most count times.
  14477. *
  14478. * <img src="./img/repeat.png" width="100%">
  14479. *
  14480. * @param {number} [count] The number of times the source Observable items are repeated, a count of 0 will yield
  14481. * an empty Observable.
  14482. * @return {Observable} An Observable that repeats the stream of items emitted by the source Observable at most
  14483. * count times.
  14484. * @method repeat
  14485. * @owner Observable
  14486. */
  14487. function repeat$1(count) {
  14488. if (count === void 0) { count = -1; }
  14489. return function (source) {
  14490. if (count === 0) {
  14491. return new EmptyObservable();
  14492. }
  14493. else if (count < 0) {
  14494. return source.lift(new RepeatOperator(-1, source));
  14495. }
  14496. else {
  14497. return source.lift(new RepeatOperator(count - 1, source));
  14498. }
  14499. };
  14500. }
  14501. var RepeatOperator = (function () {
  14502. function RepeatOperator(count, source) {
  14503. this.count = count;
  14504. this.source = source;
  14505. }
  14506. RepeatOperator.prototype.call = function (subscriber, source) {
  14507. return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));
  14508. };
  14509. return RepeatOperator;
  14510. }());
  14511. /**
  14512. * We need this JSDoc comment for affecting ESDoc.
  14513. * @ignore
  14514. * @extends {Ignored}
  14515. */
  14516. var RepeatSubscriber = (function (_super) {
  14517. __extends(RepeatSubscriber, _super);
  14518. function RepeatSubscriber(destination, count, source) {
  14519. _super.call(this, destination);
  14520. this.count = count;
  14521. this.source = source;
  14522. }
  14523. RepeatSubscriber.prototype.complete = function () {
  14524. if (!this.isStopped) {
  14525. var _a = this, source = _a.source, count = _a.count;
  14526. if (count === 0) {
  14527. return _super.prototype.complete.call(this);
  14528. }
  14529. else if (count > -1) {
  14530. this.count = count - 1;
  14531. }
  14532. source.subscribe(this._unsubscribeAndRecycle());
  14533. }
  14534. };
  14535. return RepeatSubscriber;
  14536. }(Subscriber));
  14537. /**
  14538. * Returns an Observable that repeats the stream of items emitted by the source Observable at most count times.
  14539. *
  14540. * <img src="./img/repeat.png" width="100%">
  14541. *
  14542. * @param {number} [count] The number of times the source Observable items are repeated, a count of 0 will yield
  14543. * an empty Observable.
  14544. * @return {Observable} An Observable that repeats the stream of items emitted by the source Observable at most
  14545. * count times.
  14546. * @method repeat
  14547. * @owner Observable
  14548. */
  14549. function repeat$$1(count) {
  14550. if (count === void 0) { count = -1; }
  14551. return repeat$1(count)(this);
  14552. }
  14553. Observable.prototype.repeat = repeat$$1;
  14554. /**
  14555. * Returns an Observable that mirrors the source Observable with the exception of a `complete`. If the source
  14556. * Observable calls `complete`, this method will emit to the Observable returned from `notifier`. If that Observable
  14557. * calls `complete` or `error`, then this method will call `complete` or `error` on the child subscription. Otherwise
  14558. * this method will resubscribe to the source Observable.
  14559. *
  14560. * <img src="./img/repeatWhen.png" width="100%">
  14561. *
  14562. * @param {function(notifications: Observable): Observable} notifier - Receives an Observable of notifications with
  14563. * which a user can `complete` or `error`, aborting the repetition.
  14564. * @return {Observable} The source Observable modified with repeat logic.
  14565. * @method repeatWhen
  14566. * @owner Observable
  14567. */
  14568. function repeatWhen$1(notifier) {
  14569. return function (source) { return source.lift(new RepeatWhenOperator(notifier)); };
  14570. }
  14571. var RepeatWhenOperator = (function () {
  14572. function RepeatWhenOperator(notifier) {
  14573. this.notifier = notifier;
  14574. }
  14575. RepeatWhenOperator.prototype.call = function (subscriber, source) {
  14576. return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));
  14577. };
  14578. return RepeatWhenOperator;
  14579. }());
  14580. /**
  14581. * We need this JSDoc comment for affecting ESDoc.
  14582. * @ignore
  14583. * @extends {Ignored}
  14584. */
  14585. var RepeatWhenSubscriber = (function (_super) {
  14586. __extends(RepeatWhenSubscriber, _super);
  14587. function RepeatWhenSubscriber(destination, notifier, source) {
  14588. _super.call(this, destination);
  14589. this.notifier = notifier;
  14590. this.source = source;
  14591. this.sourceIsBeingSubscribedTo = true;
  14592. }
  14593. RepeatWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  14594. this.sourceIsBeingSubscribedTo = true;
  14595. this.source.subscribe(this);
  14596. };
  14597. RepeatWhenSubscriber.prototype.notifyComplete = function (innerSub) {
  14598. if (this.sourceIsBeingSubscribedTo === false) {
  14599. return _super.prototype.complete.call(this);
  14600. }
  14601. };
  14602. RepeatWhenSubscriber.prototype.complete = function () {
  14603. this.sourceIsBeingSubscribedTo = false;
  14604. if (!this.isStopped) {
  14605. if (!this.retries) {
  14606. this.subscribeToRetries();
  14607. }
  14608. if (!this.retriesSubscription || this.retriesSubscription.closed) {
  14609. return _super.prototype.complete.call(this);
  14610. }
  14611. this._unsubscribeAndRecycle();
  14612. this.notifications.next();
  14613. }
  14614. };
  14615. /** @deprecated internal use only */ RepeatWhenSubscriber.prototype._unsubscribe = function () {
  14616. var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription;
  14617. if (notifications) {
  14618. notifications.unsubscribe();
  14619. this.notifications = null;
  14620. }
  14621. if (retriesSubscription) {
  14622. retriesSubscription.unsubscribe();
  14623. this.retriesSubscription = null;
  14624. }
  14625. this.retries = null;
  14626. };
  14627. /** @deprecated internal use only */ RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () {
  14628. var _a = this, notifications = _a.notifications, retries = _a.retries, retriesSubscription = _a.retriesSubscription;
  14629. this.notifications = null;
  14630. this.retries = null;
  14631. this.retriesSubscription = null;
  14632. _super.prototype._unsubscribeAndRecycle.call(this);
  14633. this.notifications = notifications;
  14634. this.retries = retries;
  14635. this.retriesSubscription = retriesSubscription;
  14636. return this;
  14637. };
  14638. RepeatWhenSubscriber.prototype.subscribeToRetries = function () {
  14639. this.notifications = new Subject();
  14640. var retries = tryCatch(this.notifier)(this.notifications);
  14641. if (retries === errorObject) {
  14642. return _super.prototype.complete.call(this);
  14643. }
  14644. this.retries = retries;
  14645. this.retriesSubscription = subscribeToResult(this, retries);
  14646. };
  14647. return RepeatWhenSubscriber;
  14648. }(OuterSubscriber));
  14649. /**
  14650. * Returns an Observable that mirrors the source Observable with the exception of a `complete`. If the source
  14651. * Observable calls `complete`, this method will emit to the Observable returned from `notifier`. If that Observable
  14652. * calls `complete` or `error`, then this method will call `complete` or `error` on the child subscription. Otherwise
  14653. * this method will resubscribe to the source Observable.
  14654. *
  14655. * <img src="./img/repeatWhen.png" width="100%">
  14656. *
  14657. * @param {function(notifications: Observable): Observable} notifier - Receives an Observable of notifications with
  14658. * which a user can `complete` or `error`, aborting the repetition.
  14659. * @return {Observable} The source Observable modified with repeat logic.
  14660. * @method repeatWhen
  14661. * @owner Observable
  14662. */
  14663. function repeatWhen$$1(notifier) {
  14664. return repeatWhen$1(notifier)(this);
  14665. }
  14666. Observable.prototype.repeatWhen = repeatWhen$$1;
  14667. /**
  14668. * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
  14669. * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
  14670. * as a number parameter) rather than propagating the `error` call.
  14671. *
  14672. * <img src="./img/retry.png" width="100%">
  14673. *
  14674. * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
  14675. * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
  14676. * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
  14677. * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
  14678. * @param {number} count - Number of retry attempts before failing.
  14679. * @return {Observable} The source Observable modified with the retry logic.
  14680. * @method retry
  14681. * @owner Observable
  14682. */
  14683. function retry$1(count) {
  14684. if (count === void 0) { count = -1; }
  14685. return function (source) { return source.lift(new RetryOperator(count, source)); };
  14686. }
  14687. var RetryOperator = (function () {
  14688. function RetryOperator(count, source) {
  14689. this.count = count;
  14690. this.source = source;
  14691. }
  14692. RetryOperator.prototype.call = function (subscriber, source) {
  14693. return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
  14694. };
  14695. return RetryOperator;
  14696. }());
  14697. /**
  14698. * We need this JSDoc comment for affecting ESDoc.
  14699. * @ignore
  14700. * @extends {Ignored}
  14701. */
  14702. var RetrySubscriber = (function (_super) {
  14703. __extends(RetrySubscriber, _super);
  14704. function RetrySubscriber(destination, count, source) {
  14705. _super.call(this, destination);
  14706. this.count = count;
  14707. this.source = source;
  14708. }
  14709. RetrySubscriber.prototype.error = function (err) {
  14710. if (!this.isStopped) {
  14711. var _a = this, source = _a.source, count = _a.count;
  14712. if (count === 0) {
  14713. return _super.prototype.error.call(this, err);
  14714. }
  14715. else if (count > -1) {
  14716. this.count = count - 1;
  14717. }
  14718. source.subscribe(this._unsubscribeAndRecycle());
  14719. }
  14720. };
  14721. return RetrySubscriber;
  14722. }(Subscriber));
  14723. /**
  14724. * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
  14725. * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
  14726. * as a number parameter) rather than propagating the `error` call.
  14727. *
  14728. * <img src="./img/retry.png" width="100%">
  14729. *
  14730. * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
  14731. * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
  14732. * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
  14733. * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
  14734. * @param {number} count - Number of retry attempts before failing.
  14735. * @return {Observable} The source Observable modified with the retry logic.
  14736. * @method retry
  14737. * @owner Observable
  14738. */
  14739. function retry$$1(count) {
  14740. if (count === void 0) { count = -1; }
  14741. return retry$1(count)(this);
  14742. }
  14743. Observable.prototype.retry = retry$$1;
  14744. /**
  14745. * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
  14746. * calls `error`, this method will emit the Throwable that caused the error to the Observable returned from `notifier`.
  14747. * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child
  14748. * subscription. Otherwise this method will resubscribe to the source Observable.
  14749. *
  14750. * <img src="./img/retryWhen.png" width="100%">
  14751. *
  14752. * @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a
  14753. * user can `complete` or `error`, aborting the retry.
  14754. * @return {Observable} The source Observable modified with retry logic.
  14755. * @method retryWhen
  14756. * @owner Observable
  14757. */
  14758. function retryWhen$1(notifier) {
  14759. return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); };
  14760. }
  14761. var RetryWhenOperator = (function () {
  14762. function RetryWhenOperator(notifier, source) {
  14763. this.notifier = notifier;
  14764. this.source = source;
  14765. }
  14766. RetryWhenOperator.prototype.call = function (subscriber, source) {
  14767. return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
  14768. };
  14769. return RetryWhenOperator;
  14770. }());
  14771. /**
  14772. * We need this JSDoc comment for affecting ESDoc.
  14773. * @ignore
  14774. * @extends {Ignored}
  14775. */
  14776. var RetryWhenSubscriber = (function (_super) {
  14777. __extends(RetryWhenSubscriber, _super);
  14778. function RetryWhenSubscriber(destination, notifier, source) {
  14779. _super.call(this, destination);
  14780. this.notifier = notifier;
  14781. this.source = source;
  14782. }
  14783. RetryWhenSubscriber.prototype.error = function (err) {
  14784. if (!this.isStopped) {
  14785. var errors = this.errors;
  14786. var retries = this.retries;
  14787. var retriesSubscription = this.retriesSubscription;
  14788. if (!retries) {
  14789. errors = new Subject();
  14790. retries = tryCatch(this.notifier)(errors);
  14791. if (retries === errorObject) {
  14792. return _super.prototype.error.call(this, errorObject.e);
  14793. }
  14794. retriesSubscription = subscribeToResult(this, retries);
  14795. }
  14796. else {
  14797. this.errors = null;
  14798. this.retriesSubscription = null;
  14799. }
  14800. this._unsubscribeAndRecycle();
  14801. this.errors = errors;
  14802. this.retries = retries;
  14803. this.retriesSubscription = retriesSubscription;
  14804. errors.next(err);
  14805. }
  14806. };
  14807. /** @deprecated internal use only */ RetryWhenSubscriber.prototype._unsubscribe = function () {
  14808. var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
  14809. if (errors) {
  14810. errors.unsubscribe();
  14811. this.errors = null;
  14812. }
  14813. if (retriesSubscription) {
  14814. retriesSubscription.unsubscribe();
  14815. this.retriesSubscription = null;
  14816. }
  14817. this.retries = null;
  14818. };
  14819. RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  14820. var _a = this, errors = _a.errors, retries = _a.retries, retriesSubscription = _a.retriesSubscription;
  14821. this.errors = null;
  14822. this.retries = null;
  14823. this.retriesSubscription = null;
  14824. this._unsubscribeAndRecycle();
  14825. this.errors = errors;
  14826. this.retries = retries;
  14827. this.retriesSubscription = retriesSubscription;
  14828. this.source.subscribe(this);
  14829. };
  14830. return RetryWhenSubscriber;
  14831. }(OuterSubscriber));
  14832. /**
  14833. * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
  14834. * calls `error`, this method will emit the Throwable that caused the error to the Observable returned from `notifier`.
  14835. * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child
  14836. * subscription. Otherwise this method will resubscribe to the source Observable.
  14837. *
  14838. * <img src="./img/retryWhen.png" width="100%">
  14839. *
  14840. * @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a
  14841. * user can `complete` or `error`, aborting the retry.
  14842. * @return {Observable} The source Observable modified with retry logic.
  14843. * @method retryWhen
  14844. * @owner Observable
  14845. */
  14846. function retryWhen$$1(notifier) {
  14847. return retryWhen$1(notifier)(this);
  14848. }
  14849. Observable.prototype.retryWhen = retryWhen$$1;
  14850. /**
  14851. * Emits the most recently emitted value from the source Observable whenever
  14852. * another Observable, the `notifier`, emits.
  14853. *
  14854. * <span class="informal">It's like {@link sampleTime}, but samples whenever
  14855. * the `notifier` Observable emits something.</span>
  14856. *
  14857. * <img src="./img/sample.png" width="100%">
  14858. *
  14859. * Whenever the `notifier` Observable emits a value or completes, `sample`
  14860. * looks at the source Observable and emits whichever value it has most recently
  14861. * emitted since the previous sampling, unless the source has not emitted
  14862. * anything since the previous sampling. The `notifier` is subscribed to as soon
  14863. * as the output Observable is subscribed.
  14864. *
  14865. * @example <caption>On every click, sample the most recent "seconds" timer</caption>
  14866. * var seconds = Rx.Observable.interval(1000);
  14867. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14868. * var result = seconds.sample(clicks);
  14869. * result.subscribe(x => console.log(x));
  14870. *
  14871. * @see {@link audit}
  14872. * @see {@link debounce}
  14873. * @see {@link sampleTime}
  14874. * @see {@link throttle}
  14875. *
  14876. * @param {Observable<any>} notifier The Observable to use for sampling the
  14877. * source Observable.
  14878. * @return {Observable<T>} An Observable that emits the results of sampling the
  14879. * values emitted by the source Observable whenever the notifier Observable
  14880. * emits value or completes.
  14881. * @method sample
  14882. * @owner Observable
  14883. */
  14884. function sample$1(notifier) {
  14885. return function (source) { return source.lift(new SampleOperator(notifier)); };
  14886. }
  14887. var SampleOperator = (function () {
  14888. function SampleOperator(notifier) {
  14889. this.notifier = notifier;
  14890. }
  14891. SampleOperator.prototype.call = function (subscriber, source) {
  14892. var sampleSubscriber = new SampleSubscriber(subscriber);
  14893. var subscription = source.subscribe(sampleSubscriber);
  14894. subscription.add(subscribeToResult(sampleSubscriber, this.notifier));
  14895. return subscription;
  14896. };
  14897. return SampleOperator;
  14898. }());
  14899. /**
  14900. * We need this JSDoc comment for affecting ESDoc.
  14901. * @ignore
  14902. * @extends {Ignored}
  14903. */
  14904. var SampleSubscriber = (function (_super) {
  14905. __extends(SampleSubscriber, _super);
  14906. function SampleSubscriber() {
  14907. _super.apply(this, arguments);
  14908. this.hasValue = false;
  14909. }
  14910. SampleSubscriber.prototype._next = function (value) {
  14911. this.value = value;
  14912. this.hasValue = true;
  14913. };
  14914. SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  14915. this.emitValue();
  14916. };
  14917. SampleSubscriber.prototype.notifyComplete = function () {
  14918. this.emitValue();
  14919. };
  14920. SampleSubscriber.prototype.emitValue = function () {
  14921. if (this.hasValue) {
  14922. this.hasValue = false;
  14923. this.destination.next(this.value);
  14924. }
  14925. };
  14926. return SampleSubscriber;
  14927. }(OuterSubscriber));
  14928. /**
  14929. * Emits the most recently emitted value from the source Observable whenever
  14930. * another Observable, the `notifier`, emits.
  14931. *
  14932. * <span class="informal">It's like {@link sampleTime}, but samples whenever
  14933. * the `notifier` Observable emits something.</span>
  14934. *
  14935. * <img src="./img/sample.png" width="100%">
  14936. *
  14937. * Whenever the `notifier` Observable emits a value or completes, `sample`
  14938. * looks at the source Observable and emits whichever value it has most recently
  14939. * emitted since the previous sampling, unless the source has not emitted
  14940. * anything since the previous sampling. The `notifier` is subscribed to as soon
  14941. * as the output Observable is subscribed.
  14942. *
  14943. * @example <caption>On every click, sample the most recent "seconds" timer</caption>
  14944. * var seconds = Rx.Observable.interval(1000);
  14945. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14946. * var result = seconds.sample(clicks);
  14947. * result.subscribe(x => console.log(x));
  14948. *
  14949. * @see {@link audit}
  14950. * @see {@link debounce}
  14951. * @see {@link sampleTime}
  14952. * @see {@link throttle}
  14953. *
  14954. * @param {Observable<any>} notifier The Observable to use for sampling the
  14955. * source Observable.
  14956. * @return {Observable<T>} An Observable that emits the results of sampling the
  14957. * values emitted by the source Observable whenever the notifier Observable
  14958. * emits value or completes.
  14959. * @method sample
  14960. * @owner Observable
  14961. */
  14962. function sample$$1(notifier) {
  14963. return sample$1(notifier)(this);
  14964. }
  14965. Observable.prototype.sample = sample$$1;
  14966. /**
  14967. * Emits the most recently emitted value from the source Observable within
  14968. * periodic time intervals.
  14969. *
  14970. * <span class="informal">Samples the source Observable at periodic time
  14971. * intervals, emitting what it samples.</span>
  14972. *
  14973. * <img src="./img/sampleTime.png" width="100%">
  14974. *
  14975. * `sampleTime` periodically looks at the source Observable and emits whichever
  14976. * value it has most recently emitted since the previous sampling, unless the
  14977. * source has not emitted anything since the previous sampling. The sampling
  14978. * happens periodically in time every `period` milliseconds (or the time unit
  14979. * defined by the optional `scheduler` argument). The sampling starts as soon as
  14980. * the output Observable is subscribed.
  14981. *
  14982. * @example <caption>Every second, emit the most recent click at most once</caption>
  14983. * var clicks = Rx.Observable.fromEvent(document, 'click');
  14984. * var result = clicks.sampleTime(1000);
  14985. * result.subscribe(x => console.log(x));
  14986. *
  14987. * @see {@link auditTime}
  14988. * @see {@link debounceTime}
  14989. * @see {@link delay}
  14990. * @see {@link sample}
  14991. * @see {@link throttleTime}
  14992. *
  14993. * @param {number} period The sampling period expressed in milliseconds or the
  14994. * time unit determined internally by the optional `scheduler`.
  14995. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  14996. * managing the timers that handle the sampling.
  14997. * @return {Observable<T>} An Observable that emits the results of sampling the
  14998. * values emitted by the source Observable at the specified time interval.
  14999. * @method sampleTime
  15000. * @owner Observable
  15001. */
  15002. function sampleTime$1(period, scheduler) {
  15003. if (scheduler === void 0) { scheduler = async; }
  15004. return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); };
  15005. }
  15006. var SampleTimeOperator = (function () {
  15007. function SampleTimeOperator(period, scheduler) {
  15008. this.period = period;
  15009. this.scheduler = scheduler;
  15010. }
  15011. SampleTimeOperator.prototype.call = function (subscriber, source) {
  15012. return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));
  15013. };
  15014. return SampleTimeOperator;
  15015. }());
  15016. /**
  15017. * We need this JSDoc comment for affecting ESDoc.
  15018. * @ignore
  15019. * @extends {Ignored}
  15020. */
  15021. var SampleTimeSubscriber = (function (_super) {
  15022. __extends(SampleTimeSubscriber, _super);
  15023. function SampleTimeSubscriber(destination, period, scheduler) {
  15024. _super.call(this, destination);
  15025. this.period = period;
  15026. this.scheduler = scheduler;
  15027. this.hasValue = false;
  15028. this.add(scheduler.schedule(dispatchNotification, period, { subscriber: this, period: period }));
  15029. }
  15030. SampleTimeSubscriber.prototype._next = function (value) {
  15031. this.lastValue = value;
  15032. this.hasValue = true;
  15033. };
  15034. SampleTimeSubscriber.prototype.notifyNext = function () {
  15035. if (this.hasValue) {
  15036. this.hasValue = false;
  15037. this.destination.next(this.lastValue);
  15038. }
  15039. };
  15040. return SampleTimeSubscriber;
  15041. }(Subscriber));
  15042. function dispatchNotification(state) {
  15043. var subscriber = state.subscriber, period = state.period;
  15044. subscriber.notifyNext();
  15045. this.schedule(state, period);
  15046. }
  15047. /**
  15048. * Emits the most recently emitted value from the source Observable within
  15049. * periodic time intervals.
  15050. *
  15051. * <span class="informal">Samples the source Observable at periodic time
  15052. * intervals, emitting what it samples.</span>
  15053. *
  15054. * <img src="./img/sampleTime.png" width="100%">
  15055. *
  15056. * `sampleTime` periodically looks at the source Observable and emits whichever
  15057. * value it has most recently emitted since the previous sampling, unless the
  15058. * source has not emitted anything since the previous sampling. The sampling
  15059. * happens periodically in time every `period` milliseconds (or the time unit
  15060. * defined by the optional `scheduler` argument). The sampling starts as soon as
  15061. * the output Observable is subscribed.
  15062. *
  15063. * @example <caption>Every second, emit the most recent click at most once</caption>
  15064. * var clicks = Rx.Observable.fromEvent(document, 'click');
  15065. * var result = clicks.sampleTime(1000);
  15066. * result.subscribe(x => console.log(x));
  15067. *
  15068. * @see {@link auditTime}
  15069. * @see {@link debounceTime}
  15070. * @see {@link delay}
  15071. * @see {@link sample}
  15072. * @see {@link throttleTime}
  15073. *
  15074. * @param {number} period The sampling period expressed in milliseconds or the
  15075. * time unit determined internally by the optional `scheduler`.
  15076. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  15077. * managing the timers that handle the sampling.
  15078. * @return {Observable<T>} An Observable that emits the results of sampling the
  15079. * values emitted by the source Observable at the specified time interval.
  15080. * @method sampleTime
  15081. * @owner Observable
  15082. */
  15083. function sampleTime$$1(period, scheduler) {
  15084. if (scheduler === void 0) { scheduler = async; }
  15085. return sampleTime$1(period, scheduler)(this);
  15086. }
  15087. Observable.prototype.sampleTime = sampleTime$$1;
  15088. /* tslint:enable:max-line-length */
  15089. /**
  15090. * Applies an accumulator function over the source Observable, and returns each
  15091. * intermediate result, with an optional seed value.
  15092. *
  15093. * <span class="informal">It's like {@link reduce}, but emits the current
  15094. * accumulation whenever the source emits a value.</span>
  15095. *
  15096. * <img src="./img/scan.png" width="100%">
  15097. *
  15098. * Combines together all values emitted on the source, using an accumulator
  15099. * function that knows how to join a new source value into the accumulation from
  15100. * the past. Is similar to {@link reduce}, but emits the intermediate
  15101. * accumulations.
  15102. *
  15103. * Returns an Observable that applies a specified `accumulator` function to each
  15104. * item emitted by the source Observable. If a `seed` value is specified, then
  15105. * that value will be used as the initial value for the accumulator. If no seed
  15106. * value is specified, the first item of the source is used as the seed.
  15107. *
  15108. * @example <caption>Count the number of click events</caption>
  15109. * var clicks = Rx.Observable.fromEvent(document, 'click');
  15110. * var ones = clicks.mapTo(1);
  15111. * var seed = 0;
  15112. * var count = ones.scan((acc, one) => acc + one, seed);
  15113. * count.subscribe(x => console.log(x));
  15114. *
  15115. * @see {@link expand}
  15116. * @see {@link mergeScan}
  15117. * @see {@link reduce}
  15118. *
  15119. * @param {function(acc: R, value: T, index: number): R} accumulator
  15120. * The accumulator function called on each source value.
  15121. * @param {T|R} [seed] The initial accumulation value.
  15122. * @return {Observable<R>} An observable of the accumulated values.
  15123. * @method scan
  15124. * @owner Observable
  15125. */
  15126. function scan$1(accumulator, seed) {
  15127. if (arguments.length >= 2) {
  15128. return scan(accumulator, seed)(this);
  15129. }
  15130. return scan(accumulator)(this);
  15131. }
  15132. Observable.prototype.scan = scan$1;
  15133. /**
  15134. * Compares all values of two observables in sequence using an optional comparor function
  15135. * and returns an observable of a single boolean value representing whether or not the two sequences
  15136. * are equal.
  15137. *
  15138. * <span class="informal">Checks to see of all values emitted by both observables are equal, in order.</span>
  15139. *
  15140. * <img src="./img/sequenceEqual.png" width="100%">
  15141. *
  15142. * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either
  15143. * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom
  15144. * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the
  15145. * observables completes, the operator will wait for the other observable to complete; If the other
  15146. * observable emits before completing, the returned observable will emit `false` and complete. If one observable never
  15147. * completes or emits after the other complets, the returned observable will never complete.
  15148. *
  15149. * @example <caption>figure out if the Konami code matches</caption>
  15150. * var code = Rx.Observable.from([
  15151. * "ArrowUp",
  15152. * "ArrowUp",
  15153. * "ArrowDown",
  15154. * "ArrowDown",
  15155. * "ArrowLeft",
  15156. * "ArrowRight",
  15157. * "ArrowLeft",
  15158. * "ArrowRight",
  15159. * "KeyB",
  15160. * "KeyA",
  15161. * "Enter" // no start key, clearly.
  15162. * ]);
  15163. *
  15164. * var keys = Rx.Observable.fromEvent(document, 'keyup')
  15165. * .map(e => e.code);
  15166. * var matches = keys.bufferCount(11, 1)
  15167. * .mergeMap(
  15168. * last11 =>
  15169. * Rx.Observable.from(last11)
  15170. * .sequenceEqual(code)
  15171. * );
  15172. * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));
  15173. *
  15174. * @see {@link combineLatest}
  15175. * @see {@link zip}
  15176. * @see {@link withLatestFrom}
  15177. *
  15178. * @param {Observable} compareTo The observable sequence to compare the source sequence to.
  15179. * @param {function} [comparor] An optional function to compare each value pair
  15180. * @return {Observable} An Observable of a single boolean value representing whether or not
  15181. * the values emitted by both observables were equal in sequence.
  15182. * @method sequenceEqual
  15183. * @owner Observable
  15184. */
  15185. function sequenceEqual$1(compareTo, comparor) {
  15186. return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparor)); };
  15187. }
  15188. var SequenceEqualOperator = (function () {
  15189. function SequenceEqualOperator(compareTo, comparor) {
  15190. this.compareTo = compareTo;
  15191. this.comparor = comparor;
  15192. }
  15193. SequenceEqualOperator.prototype.call = function (subscriber, source) {
  15194. return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor));
  15195. };
  15196. return SequenceEqualOperator;
  15197. }());
  15198. /**
  15199. * We need this JSDoc comment for affecting ESDoc.
  15200. * @ignore
  15201. * @extends {Ignored}
  15202. */
  15203. var SequenceEqualSubscriber = (function (_super) {
  15204. __extends(SequenceEqualSubscriber, _super);
  15205. function SequenceEqualSubscriber(destination, compareTo, comparor) {
  15206. _super.call(this, destination);
  15207. this.compareTo = compareTo;
  15208. this.comparor = comparor;
  15209. this._a = [];
  15210. this._b = [];
  15211. this._oneComplete = false;
  15212. this.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this)));
  15213. }
  15214. SequenceEqualSubscriber.prototype._next = function (value) {
  15215. if (this._oneComplete && this._b.length === 0) {
  15216. this.emit(false);
  15217. }
  15218. else {
  15219. this._a.push(value);
  15220. this.checkValues();
  15221. }
  15222. };
  15223. SequenceEqualSubscriber.prototype._complete = function () {
  15224. if (this._oneComplete) {
  15225. this.emit(this._a.length === 0 && this._b.length === 0);
  15226. }
  15227. else {
  15228. this._oneComplete = true;
  15229. }
  15230. };
  15231. SequenceEqualSubscriber.prototype.checkValues = function () {
  15232. var _c = this, _a = _c._a, _b = _c._b, comparor = _c.comparor;
  15233. while (_a.length > 0 && _b.length > 0) {
  15234. var a = _a.shift();
  15235. var b = _b.shift();
  15236. var areEqual = false;
  15237. if (comparor) {
  15238. areEqual = tryCatch(comparor)(a, b);
  15239. if (areEqual === errorObject) {
  15240. this.destination.error(errorObject.e);
  15241. }
  15242. }
  15243. else {
  15244. areEqual = a === b;
  15245. }
  15246. if (!areEqual) {
  15247. this.emit(false);
  15248. }
  15249. }
  15250. };
  15251. SequenceEqualSubscriber.prototype.emit = function (value) {
  15252. var destination = this.destination;
  15253. destination.next(value);
  15254. destination.complete();
  15255. };
  15256. SequenceEqualSubscriber.prototype.nextB = function (value) {
  15257. if (this._oneComplete && this._a.length === 0) {
  15258. this.emit(false);
  15259. }
  15260. else {
  15261. this._b.push(value);
  15262. this.checkValues();
  15263. }
  15264. };
  15265. return SequenceEqualSubscriber;
  15266. }(Subscriber));
  15267. var SequenceEqualCompareToSubscriber = (function (_super) {
  15268. __extends(SequenceEqualCompareToSubscriber, _super);
  15269. function SequenceEqualCompareToSubscriber(destination, parent) {
  15270. _super.call(this, destination);
  15271. this.parent = parent;
  15272. }
  15273. SequenceEqualCompareToSubscriber.prototype._next = function (value) {
  15274. this.parent.nextB(value);
  15275. };
  15276. SequenceEqualCompareToSubscriber.prototype._error = function (err) {
  15277. this.parent.error(err);
  15278. };
  15279. SequenceEqualCompareToSubscriber.prototype._complete = function () {
  15280. this.parent._complete();
  15281. };
  15282. return SequenceEqualCompareToSubscriber;
  15283. }(Subscriber));
  15284. /**
  15285. * Compares all values of two observables in sequence using an optional comparor function
  15286. * and returns an observable of a single boolean value representing whether or not the two sequences
  15287. * are equal.
  15288. *
  15289. * <span class="informal">Checks to see of all values emitted by both observables are equal, in order.</span>
  15290. *
  15291. * <img src="./img/sequenceEqual.png" width="100%">
  15292. *
  15293. * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either
  15294. * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom
  15295. * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the
  15296. * observables completes, the operator will wait for the other observable to complete; If the other
  15297. * observable emits before completing, the returned observable will emit `false` and complete. If one observable never
  15298. * completes or emits after the other complets, the returned observable will never complete.
  15299. *
  15300. * @example <caption>figure out if the Konami code matches</caption>
  15301. * var code = Rx.Observable.from([
  15302. * "ArrowUp",
  15303. * "ArrowUp",
  15304. * "ArrowDown",
  15305. * "ArrowDown",
  15306. * "ArrowLeft",
  15307. * "ArrowRight",
  15308. * "ArrowLeft",
  15309. * "ArrowRight",
  15310. * "KeyB",
  15311. * "KeyA",
  15312. * "Enter" // no start key, clearly.
  15313. * ]);
  15314. *
  15315. * var keys = Rx.Observable.fromEvent(document, 'keyup')
  15316. * .map(e => e.code);
  15317. * var matches = keys.bufferCount(11, 1)
  15318. * .mergeMap(
  15319. * last11 =>
  15320. * Rx.Observable.from(last11)
  15321. * .sequenceEqual(code)
  15322. * );
  15323. * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));
  15324. *
  15325. * @see {@link combineLatest}
  15326. * @see {@link zip}
  15327. * @see {@link withLatestFrom}
  15328. *
  15329. * @param {Observable} compareTo The observable sequence to compare the source sequence to.
  15330. * @param {function} [comparor] An optional function to compare each value pair
  15331. * @return {Observable} An Observable of a single boolean value representing whether or not
  15332. * the values emitted by both observables were equal in sequence.
  15333. * @method sequenceEqual
  15334. * @owner Observable
  15335. */
  15336. function sequenceEqual$$1(compareTo, comparor) {
  15337. return sequenceEqual$1(compareTo, comparor)(this);
  15338. }
  15339. Observable.prototype.sequenceEqual = sequenceEqual$$1;
  15340. function shareSubjectFactory() {
  15341. return new Subject();
  15342. }
  15343. /**
  15344. * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
  15345. * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
  15346. * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
  15347. * This is an alias for .multicast(() => new Subject()).refCount().
  15348. *
  15349. * <img src="./img/share.png" width="100%">
  15350. *
  15351. * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
  15352. * @method share
  15353. * @owner Observable
  15354. */
  15355. function share$1() {
  15356. return function (source) { return refCount()(multicast$1(shareSubjectFactory)(source)); };
  15357. }
  15358. /**
  15359. * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
  15360. * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
  15361. * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
  15362. *
  15363. * This behaves similarly to .publish().refCount(), with a behavior difference when the source observable emits complete.
  15364. * .publish().refCount() will not resubscribe to the original source, however .share() will resubscribe to the original source.
  15365. * Observable.of("test").publish().refCount() will not re-emit "test" on new subscriptions, Observable.of("test").share() will
  15366. * re-emit "test" to new subscriptions.
  15367. *
  15368. * <img src="./img/share.png" width="100%">
  15369. *
  15370. * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
  15371. * @method share
  15372. * @owner Observable
  15373. */
  15374. function share$$1() {
  15375. return share$1()(this);
  15376. }
  15377. Observable.prototype.share = share$$1;
  15378. /**
  15379. * @method shareReplay
  15380. * @owner Observable
  15381. */
  15382. function shareReplay$1(bufferSize, windowTime, scheduler) {
  15383. return function (source) { return source.lift(shareReplayOperator(bufferSize, windowTime, scheduler)); };
  15384. }
  15385. function shareReplayOperator(bufferSize, windowTime, scheduler) {
  15386. var subject;
  15387. var refCount = 0;
  15388. var subscription;
  15389. var hasError = false;
  15390. var isComplete = false;
  15391. return function shareReplayOperation(source) {
  15392. refCount++;
  15393. if (!subject || hasError) {
  15394. hasError = false;
  15395. subject = new ReplaySubject(bufferSize, windowTime, scheduler);
  15396. subscription = source.subscribe({
  15397. next: function (value) { subject.next(value); },
  15398. error: function (err) {
  15399. hasError = true;
  15400. subject.error(err);
  15401. },
  15402. complete: function () {
  15403. isComplete = true;
  15404. subject.complete();
  15405. },
  15406. });
  15407. }
  15408. var innerSub = subject.subscribe(this);
  15409. return function () {
  15410. refCount--;
  15411. innerSub.unsubscribe();
  15412. if (subscription && refCount === 0 && isComplete) {
  15413. subscription.unsubscribe();
  15414. }
  15415. };
  15416. };
  15417. }
  15418. /**
  15419. * @method shareReplay
  15420. * @owner Observable
  15421. */
  15422. function shareReplay$$1(bufferSize, windowTime, scheduler) {
  15423. return shareReplay$1(bufferSize, windowTime, scheduler)(this);
  15424. }
  15425. Observable.prototype.shareReplay = shareReplay$$1;
  15426. /**
  15427. * Returns an Observable that emits the single item emitted by the source Observable that matches a specified
  15428. * predicate, if that Observable emits one such item. If the source Observable emits more than one such item or no
  15429. * such items, notify of an IllegalArgumentException or NoSuchElementException respectively.
  15430. *
  15431. * <img src="./img/single.png" width="100%">
  15432. *
  15433. * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
  15434. * callback if the Observable completes before any `next` notification was sent.
  15435. * @param {Function} predicate - A predicate function to evaluate items emitted by the source Observable.
  15436. * @return {Observable<T>} An Observable that emits the single item emitted by the source Observable that matches
  15437. * the predicate.
  15438. .
  15439. * @method single
  15440. * @owner Observable
  15441. */
  15442. function single$1(predicate) {
  15443. return function (source) { return source.lift(new SingleOperator(predicate, source)); };
  15444. }
  15445. var SingleOperator = (function () {
  15446. function SingleOperator(predicate, source) {
  15447. this.predicate = predicate;
  15448. this.source = source;
  15449. }
  15450. SingleOperator.prototype.call = function (subscriber, source) {
  15451. return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
  15452. };
  15453. return SingleOperator;
  15454. }());
  15455. /**
  15456. * We need this JSDoc comment for affecting ESDoc.
  15457. * @ignore
  15458. * @extends {Ignored}
  15459. */
  15460. var SingleSubscriber = (function (_super) {
  15461. __extends(SingleSubscriber, _super);
  15462. function SingleSubscriber(destination, predicate, source) {
  15463. _super.call(this, destination);
  15464. this.predicate = predicate;
  15465. this.source = source;
  15466. this.seenValue = false;
  15467. this.index = 0;
  15468. }
  15469. SingleSubscriber.prototype.applySingleValue = function (value) {
  15470. if (this.seenValue) {
  15471. this.destination.error('Sequence contains more than one element');
  15472. }
  15473. else {
  15474. this.seenValue = true;
  15475. this.singleValue = value;
  15476. }
  15477. };
  15478. SingleSubscriber.prototype._next = function (value) {
  15479. var index = this.index++;
  15480. if (this.predicate) {
  15481. this.tryNext(value, index);
  15482. }
  15483. else {
  15484. this.applySingleValue(value);
  15485. }
  15486. };
  15487. SingleSubscriber.prototype.tryNext = function (value, index) {
  15488. try {
  15489. if (this.predicate(value, index, this.source)) {
  15490. this.applySingleValue(value);
  15491. }
  15492. }
  15493. catch (err) {
  15494. this.destination.error(err);
  15495. }
  15496. };
  15497. SingleSubscriber.prototype._complete = function () {
  15498. var destination = this.destination;
  15499. if (this.index > 0) {
  15500. destination.next(this.seenValue ? this.singleValue : undefined);
  15501. destination.complete();
  15502. }
  15503. else {
  15504. destination.error(new EmptyError);
  15505. }
  15506. };
  15507. return SingleSubscriber;
  15508. }(Subscriber));
  15509. /**
  15510. * Returns an Observable that emits the single item emitted by the source Observable that matches a specified
  15511. * predicate, if that Observable emits one such item. If the source Observable emits more than one such item or no
  15512. * such items, notify of an IllegalArgumentException or NoSuchElementException respectively.
  15513. *
  15514. * <img src="./img/single.png" width="100%">
  15515. *
  15516. * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
  15517. * callback if the Observable completes before any `next` notification was sent.
  15518. * @param {Function} predicate - A predicate function to evaluate items emitted by the source Observable.
  15519. * @return {Observable<T>} An Observable that emits the single item emitted by the source Observable that matches
  15520. * the predicate.
  15521. .
  15522. * @method single
  15523. * @owner Observable
  15524. */
  15525. function single$$1(predicate) {
  15526. return single$1(predicate)(this);
  15527. }
  15528. Observable.prototype.single = single$$1;
  15529. /**
  15530. * Returns an Observable that skips the first `count` items emitted by the source Observable.
  15531. *
  15532. * <img src="./img/skip.png" width="100%">
  15533. *
  15534. * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
  15535. * @return {Observable} An Observable that skips values emitted by the source Observable.
  15536. *
  15537. * @method skip
  15538. * @owner Observable
  15539. */
  15540. function skip$1(count) {
  15541. return function (source) { return source.lift(new SkipOperator(count)); };
  15542. }
  15543. var SkipOperator = (function () {
  15544. function SkipOperator(total) {
  15545. this.total = total;
  15546. }
  15547. SkipOperator.prototype.call = function (subscriber, source) {
  15548. return source.subscribe(new SkipSubscriber(subscriber, this.total));
  15549. };
  15550. return SkipOperator;
  15551. }());
  15552. /**
  15553. * We need this JSDoc comment for affecting ESDoc.
  15554. * @ignore
  15555. * @extends {Ignored}
  15556. */
  15557. var SkipSubscriber = (function (_super) {
  15558. __extends(SkipSubscriber, _super);
  15559. function SkipSubscriber(destination, total) {
  15560. _super.call(this, destination);
  15561. this.total = total;
  15562. this.count = 0;
  15563. }
  15564. SkipSubscriber.prototype._next = function (x) {
  15565. if (++this.count > this.total) {
  15566. this.destination.next(x);
  15567. }
  15568. };
  15569. return SkipSubscriber;
  15570. }(Subscriber));
  15571. /**
  15572. * Returns an Observable that skips the first `count` items emitted by the source Observable.
  15573. *
  15574. * <img src="./img/skip.png" width="100%">
  15575. *
  15576. * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
  15577. * @return {Observable} An Observable that skips values emitted by the source Observable.
  15578. *
  15579. * @method skip
  15580. * @owner Observable
  15581. */
  15582. function skip$$1(count) {
  15583. return skip$1(count)(this);
  15584. }
  15585. Observable.prototype.skip = skip$$1;
  15586. /**
  15587. * Skip the last `count` values emitted by the source Observable.
  15588. *
  15589. * <img src="./img/skipLast.png" width="100%">
  15590. *
  15591. * `skipLast` returns an Observable that accumulates a queue with a length
  15592. * enough to store the first `count` values. As more values are received,
  15593. * values are taken from the front of the queue and produced on the result
  15594. * sequence. This causes values to be delayed.
  15595. *
  15596. * @example <caption>Skip the last 2 values of an Observable with many values</caption>
  15597. * var many = Rx.Observable.range(1, 5);
  15598. * var skipLastTwo = many.skipLast(2);
  15599. * skipLastTwo.subscribe(x => console.log(x));
  15600. *
  15601. * // Results in:
  15602. * // 1 2 3
  15603. *
  15604. * @see {@link skip}
  15605. * @see {@link skipUntil}
  15606. * @see {@link skipWhile}
  15607. * @see {@link take}
  15608. *
  15609. * @throws {ArgumentOutOfRangeError} When using `skipLast(i)`, it throws
  15610. * ArgumentOutOrRangeError if `i < 0`.
  15611. *
  15612. * @param {number} count Number of elements to skip from the end of the source Observable.
  15613. * @returns {Observable<T>} An Observable that skips the last count values
  15614. * emitted by the source Observable.
  15615. * @method skipLast
  15616. * @owner Observable
  15617. */
  15618. function skipLast$1(count) {
  15619. return function (source) { return source.lift(new SkipLastOperator(count)); };
  15620. }
  15621. var SkipLastOperator = (function () {
  15622. function SkipLastOperator(_skipCount) {
  15623. this._skipCount = _skipCount;
  15624. if (this._skipCount < 0) {
  15625. throw new ArgumentOutOfRangeError;
  15626. }
  15627. }
  15628. SkipLastOperator.prototype.call = function (subscriber, source) {
  15629. if (this._skipCount === 0) {
  15630. // If we don't want to skip any values then just subscribe
  15631. // to Subscriber without any further logic.
  15632. return source.subscribe(new Subscriber(subscriber));
  15633. }
  15634. else {
  15635. return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));
  15636. }
  15637. };
  15638. return SkipLastOperator;
  15639. }());
  15640. /**
  15641. * We need this JSDoc comment for affecting ESDoc.
  15642. * @ignore
  15643. * @extends {Ignored}
  15644. */
  15645. var SkipLastSubscriber = (function (_super) {
  15646. __extends(SkipLastSubscriber, _super);
  15647. function SkipLastSubscriber(destination, _skipCount) {
  15648. _super.call(this, destination);
  15649. this._skipCount = _skipCount;
  15650. this._count = 0;
  15651. this._ring = new Array(_skipCount);
  15652. }
  15653. SkipLastSubscriber.prototype._next = function (value) {
  15654. var skipCount = this._skipCount;
  15655. var count = this._count++;
  15656. if (count < skipCount) {
  15657. this._ring[count] = value;
  15658. }
  15659. else {
  15660. var currentIndex = count % skipCount;
  15661. var ring = this._ring;
  15662. var oldValue = ring[currentIndex];
  15663. ring[currentIndex] = value;
  15664. this.destination.next(oldValue);
  15665. }
  15666. };
  15667. return SkipLastSubscriber;
  15668. }(Subscriber));
  15669. /**
  15670. * Skip the last `count` values emitted by the source Observable.
  15671. *
  15672. * <img src="./img/skipLast.png" width="100%">
  15673. *
  15674. * `skipLast` returns an Observable that accumulates a queue with a length
  15675. * enough to store the first `count` values. As more values are received,
  15676. * values are taken from the front of the queue and produced on the result
  15677. * sequence. This causes values to be delayed.
  15678. *
  15679. * @example <caption>Skip the last 2 values of an Observable with many values</caption>
  15680. * var many = Rx.Observable.range(1, 5);
  15681. * var skipLastTwo = many.skipLast(2);
  15682. * skipLastTwo.subscribe(x => console.log(x));
  15683. *
  15684. * // Results in:
  15685. * // 1 2 3
  15686. *
  15687. * @see {@link skip}
  15688. * @see {@link skipUntil}
  15689. * @see {@link skipWhile}
  15690. * @see {@link take}
  15691. *
  15692. * @throws {ArgumentOutOfRangeError} When using `skipLast(i)`, it throws
  15693. * ArgumentOutOrRangeError if `i < 0`.
  15694. *
  15695. * @param {number} count Number of elements to skip from the end of the source Observable.
  15696. * @returns {Observable<T>} An Observable that skips the last count values
  15697. * emitted by the source Observable.
  15698. * @method skipLast
  15699. * @owner Observable
  15700. */
  15701. function skipLast$$1(count) {
  15702. return skipLast$1(count)(this);
  15703. }
  15704. Observable.prototype.skipLast = skipLast$$1;
  15705. /**
  15706. * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
  15707. *
  15708. * <img src="./img/skipUntil.png" width="100%">
  15709. *
  15710. * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
  15711. * be mirrored by the resulting Observable.
  15712. * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
  15713. * an item, then emits the remaining items.
  15714. * @method skipUntil
  15715. * @owner Observable
  15716. */
  15717. function skipUntil$1(notifier) {
  15718. return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
  15719. }
  15720. var SkipUntilOperator = (function () {
  15721. function SkipUntilOperator(notifier) {
  15722. this.notifier = notifier;
  15723. }
  15724. SkipUntilOperator.prototype.call = function (subscriber, source) {
  15725. return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
  15726. };
  15727. return SkipUntilOperator;
  15728. }());
  15729. /**
  15730. * We need this JSDoc comment for affecting ESDoc.
  15731. * @ignore
  15732. * @extends {Ignored}
  15733. */
  15734. var SkipUntilSubscriber = (function (_super) {
  15735. __extends(SkipUntilSubscriber, _super);
  15736. function SkipUntilSubscriber(destination, notifier) {
  15737. _super.call(this, destination);
  15738. this.hasValue = false;
  15739. this.isInnerStopped = false;
  15740. this.add(subscribeToResult(this, notifier));
  15741. }
  15742. SkipUntilSubscriber.prototype._next = function (value) {
  15743. if (this.hasValue) {
  15744. _super.prototype._next.call(this, value);
  15745. }
  15746. };
  15747. SkipUntilSubscriber.prototype._complete = function () {
  15748. if (this.isInnerStopped) {
  15749. _super.prototype._complete.call(this);
  15750. }
  15751. else {
  15752. this.unsubscribe();
  15753. }
  15754. };
  15755. SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  15756. this.hasValue = true;
  15757. };
  15758. SkipUntilSubscriber.prototype.notifyComplete = function () {
  15759. this.isInnerStopped = true;
  15760. if (this.isStopped) {
  15761. _super.prototype._complete.call(this);
  15762. }
  15763. };
  15764. return SkipUntilSubscriber;
  15765. }(OuterSubscriber));
  15766. /**
  15767. * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
  15768. *
  15769. * <img src="./img/skipUntil.png" width="100%">
  15770. *
  15771. * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
  15772. * be mirrored by the resulting Observable.
  15773. * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
  15774. * an item, then emits the remaining items.
  15775. * @method skipUntil
  15776. * @owner Observable
  15777. */
  15778. function skipUntil$$1(notifier) {
  15779. return skipUntil$1(notifier)(this);
  15780. }
  15781. Observable.prototype.skipUntil = skipUntil$$1;
  15782. /**
  15783. * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
  15784. * true, but emits all further source items as soon as the condition becomes false.
  15785. *
  15786. * <img src="./img/skipWhile.png" width="100%">
  15787. *
  15788. * @param {Function} predicate - A function to test each item emitted from the source Observable.
  15789. * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
  15790. * specified predicate becomes false.
  15791. * @method skipWhile
  15792. * @owner Observable
  15793. */
  15794. function skipWhile$1(predicate) {
  15795. return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
  15796. }
  15797. var SkipWhileOperator = (function () {
  15798. function SkipWhileOperator(predicate) {
  15799. this.predicate = predicate;
  15800. }
  15801. SkipWhileOperator.prototype.call = function (subscriber, source) {
  15802. return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
  15803. };
  15804. return SkipWhileOperator;
  15805. }());
  15806. /**
  15807. * We need this JSDoc comment for affecting ESDoc.
  15808. * @ignore
  15809. * @extends {Ignored}
  15810. */
  15811. var SkipWhileSubscriber = (function (_super) {
  15812. __extends(SkipWhileSubscriber, _super);
  15813. function SkipWhileSubscriber(destination, predicate) {
  15814. _super.call(this, destination);
  15815. this.predicate = predicate;
  15816. this.skipping = true;
  15817. this.index = 0;
  15818. }
  15819. SkipWhileSubscriber.prototype._next = function (value) {
  15820. var destination = this.destination;
  15821. if (this.skipping) {
  15822. this.tryCallPredicate(value);
  15823. }
  15824. if (!this.skipping) {
  15825. destination.next(value);
  15826. }
  15827. };
  15828. SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
  15829. try {
  15830. var result = this.predicate(value, this.index++);
  15831. this.skipping = Boolean(result);
  15832. }
  15833. catch (err) {
  15834. this.destination.error(err);
  15835. }
  15836. };
  15837. return SkipWhileSubscriber;
  15838. }(Subscriber));
  15839. /**
  15840. * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
  15841. * true, but emits all further source items as soon as the condition becomes false.
  15842. *
  15843. * <img src="./img/skipWhile.png" width="100%">
  15844. *
  15845. * @param {Function} predicate - A function to test each item emitted from the source Observable.
  15846. * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
  15847. * specified predicate becomes false.
  15848. * @method skipWhile
  15849. * @owner Observable
  15850. */
  15851. function skipWhile$$1(predicate) {
  15852. return skipWhile$1(predicate)(this);
  15853. }
  15854. Observable.prototype.skipWhile = skipWhile$$1;
  15855. /* tslint:enable:max-line-length */
  15856. /**
  15857. * Returns an Observable that emits the items you specify as arguments before it begins to emit
  15858. * items emitted by the source Observable.
  15859. *
  15860. * <img src="./img/startWith.png" width="100%">
  15861. *
  15862. * @param {...T} values - Items you want the modified Observable to emit first.
  15863. * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
  15864. * the emissions of the `next` notifications.
  15865. * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
  15866. * emitted by the source Observable.
  15867. * @method startWith
  15868. * @owner Observable
  15869. */
  15870. function startWith$1() {
  15871. var array = [];
  15872. for (var _i = 0; _i < arguments.length; _i++) {
  15873. array[_i - 0] = arguments[_i];
  15874. }
  15875. return function (source) {
  15876. var scheduler = array[array.length - 1];
  15877. if (isScheduler(scheduler)) {
  15878. array.pop();
  15879. }
  15880. else {
  15881. scheduler = null;
  15882. }
  15883. var len = array.length;
  15884. if (len === 1) {
  15885. return concat(new ScalarObservable(array[0], scheduler), source);
  15886. }
  15887. else if (len > 1) {
  15888. return concat(new ArrayObservable(array, scheduler), source);
  15889. }
  15890. else {
  15891. return concat(new EmptyObservable(scheduler), source);
  15892. }
  15893. };
  15894. }
  15895. /* tslint:enable:max-line-length */
  15896. /**
  15897. * Returns an Observable that emits the items you specify as arguments before it begins to emit
  15898. * items emitted by the source Observable.
  15899. *
  15900. * <img src="./img/startWith.png" width="100%">
  15901. *
  15902. * @param {...T} values - Items you want the modified Observable to emit first.
  15903. * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
  15904. * the emissions of the `next` notifications.
  15905. * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
  15906. * emitted by the source Observable.
  15907. * @method startWith
  15908. * @owner Observable
  15909. */
  15910. function startWith$$1() {
  15911. var array = [];
  15912. for (var _i = 0; _i < arguments.length; _i++) {
  15913. array[_i - 0] = arguments[_i];
  15914. }
  15915. return startWith$1.apply(void 0, array)(this);
  15916. }
  15917. Observable.prototype.startWith = startWith$$1;
  15918. /**
  15919. Some credit for this helper goes to http://github.com/YuzuJS/setImmediate
  15920. */
  15921. var ImmediateDefinition = (function () {
  15922. function ImmediateDefinition(root$$1) {
  15923. this.root = root$$1;
  15924. if (root$$1.setImmediate && typeof root$$1.setImmediate === 'function') {
  15925. this.setImmediate = root$$1.setImmediate.bind(root$$1);
  15926. this.clearImmediate = root$$1.clearImmediate.bind(root$$1);
  15927. }
  15928. else {
  15929. this.nextHandle = 1;
  15930. this.tasksByHandle = {};
  15931. this.currentlyRunningATask = false;
  15932. // Don't get fooled by e.g. browserify environments.
  15933. if (this.canUseProcessNextTick()) {
  15934. // For Node.js before 0.9
  15935. this.setImmediate = this.createProcessNextTickSetImmediate();
  15936. }
  15937. else if (this.canUsePostMessage()) {
  15938. // For non-IE10 modern browsers
  15939. this.setImmediate = this.createPostMessageSetImmediate();
  15940. }
  15941. else if (this.canUseMessageChannel()) {
  15942. // For web workers, where supported
  15943. this.setImmediate = this.createMessageChannelSetImmediate();
  15944. }
  15945. else if (this.canUseReadyStateChange()) {
  15946. // For IE 6–8
  15947. this.setImmediate = this.createReadyStateChangeSetImmediate();
  15948. }
  15949. else {
  15950. // For older browsers
  15951. this.setImmediate = this.createSetTimeoutSetImmediate();
  15952. }
  15953. var ci = function clearImmediate(handle) {
  15954. delete clearImmediate.instance.tasksByHandle[handle];
  15955. };
  15956. ci.instance = this;
  15957. this.clearImmediate = ci;
  15958. }
  15959. }
  15960. ImmediateDefinition.prototype.identify = function (o) {
  15961. return this.root.Object.prototype.toString.call(o);
  15962. };
  15963. ImmediateDefinition.prototype.canUseProcessNextTick = function () {
  15964. return this.identify(this.root.process) === '[object process]';
  15965. };
  15966. ImmediateDefinition.prototype.canUseMessageChannel = function () {
  15967. return Boolean(this.root.MessageChannel);
  15968. };
  15969. ImmediateDefinition.prototype.canUseReadyStateChange = function () {
  15970. var document = this.root.document;
  15971. return Boolean(document && 'onreadystatechange' in document.createElement('script'));
  15972. };
  15973. ImmediateDefinition.prototype.canUsePostMessage = function () {
  15974. var root$$1 = this.root;
  15975. // The test against `importScripts` prevents this implementation from being installed inside a web worker,
  15976. // where `root.postMessage` means something completely different and can't be used for this purpose.
  15977. if (root$$1.postMessage && !root$$1.importScripts) {
  15978. var postMessageIsAsynchronous_1 = true;
  15979. var oldOnMessage = root$$1.onmessage;
  15980. root$$1.onmessage = function () {
  15981. postMessageIsAsynchronous_1 = false;
  15982. };
  15983. root$$1.postMessage('', '*');
  15984. root$$1.onmessage = oldOnMessage;
  15985. return postMessageIsAsynchronous_1;
  15986. }
  15987. return false;
  15988. };
  15989. // This function accepts the same arguments as setImmediate, but
  15990. // returns a function that requires no arguments.
  15991. ImmediateDefinition.prototype.partiallyApplied = function (handler) {
  15992. var args = [];
  15993. for (var _i = 1; _i < arguments.length; _i++) {
  15994. args[_i - 1] = arguments[_i];
  15995. }
  15996. var fn = function result() {
  15997. var _a = result, handler = _a.handler, args = _a.args;
  15998. if (typeof handler === 'function') {
  15999. handler.apply(undefined, args);
  16000. }
  16001. else {
  16002. (new Function('' + handler))();
  16003. }
  16004. };
  16005. fn.handler = handler;
  16006. fn.args = args;
  16007. return fn;
  16008. };
  16009. ImmediateDefinition.prototype.addFromSetImmediateArguments = function (args) {
  16010. this.tasksByHandle[this.nextHandle] = this.partiallyApplied.apply(undefined, args);
  16011. return this.nextHandle++;
  16012. };
  16013. ImmediateDefinition.prototype.createProcessNextTickSetImmediate = function () {
  16014. var fn = function setImmediate() {
  16015. var instance = setImmediate.instance;
  16016. var handle = instance.addFromSetImmediateArguments(arguments);
  16017. instance.root.process.nextTick(instance.partiallyApplied(instance.runIfPresent, handle));
  16018. return handle;
  16019. };
  16020. fn.instance = this;
  16021. return fn;
  16022. };
  16023. ImmediateDefinition.prototype.createPostMessageSetImmediate = function () {
  16024. // Installs an event handler on `global` for the `message` event: see
  16025. // * https://developer.mozilla.org/en/DOM/window.postMessage
  16026. // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
  16027. var root$$1 = this.root;
  16028. var messagePrefix = 'setImmediate$' + root$$1.Math.random() + '$';
  16029. var onGlobalMessage = function globalMessageHandler(event) {
  16030. var instance = globalMessageHandler.instance;
  16031. if (event.source === root$$1 &&
  16032. typeof event.data === 'string' &&
  16033. event.data.indexOf(messagePrefix) === 0) {
  16034. instance.runIfPresent(+event.data.slice(messagePrefix.length));
  16035. }
  16036. };
  16037. onGlobalMessage.instance = this;
  16038. root$$1.addEventListener('message', onGlobalMessage, false);
  16039. var fn = function setImmediate() {
  16040. var _a = setImmediate, messagePrefix = _a.messagePrefix, instance = _a.instance;
  16041. var handle = instance.addFromSetImmediateArguments(arguments);
  16042. instance.root.postMessage(messagePrefix + handle, '*');
  16043. return handle;
  16044. };
  16045. fn.instance = this;
  16046. fn.messagePrefix = messagePrefix;
  16047. return fn;
  16048. };
  16049. ImmediateDefinition.prototype.runIfPresent = function (handle) {
  16050. // From the spec: 'Wait until any invocations of this algorithm started before this one have completed.'
  16051. // So if we're currently running a task, we'll need to delay this invocation.
  16052. if (this.currentlyRunningATask) {
  16053. // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
  16054. // 'too much recursion' error.
  16055. this.root.setTimeout(this.partiallyApplied(this.runIfPresent, handle), 0);
  16056. }
  16057. else {
  16058. var task = this.tasksByHandle[handle];
  16059. if (task) {
  16060. this.currentlyRunningATask = true;
  16061. try {
  16062. task();
  16063. }
  16064. finally {
  16065. this.clearImmediate(handle);
  16066. this.currentlyRunningATask = false;
  16067. }
  16068. }
  16069. }
  16070. };
  16071. ImmediateDefinition.prototype.createMessageChannelSetImmediate = function () {
  16072. var _this = this;
  16073. var channel = new this.root.MessageChannel();
  16074. channel.port1.onmessage = function (event) {
  16075. var handle = event.data;
  16076. _this.runIfPresent(handle);
  16077. };
  16078. var fn = function setImmediate() {
  16079. var _a = setImmediate, channel = _a.channel, instance = _a.instance;
  16080. var handle = instance.addFromSetImmediateArguments(arguments);
  16081. channel.port2.postMessage(handle);
  16082. return handle;
  16083. };
  16084. fn.channel = channel;
  16085. fn.instance = this;
  16086. return fn;
  16087. };
  16088. ImmediateDefinition.prototype.createReadyStateChangeSetImmediate = function () {
  16089. var fn = function setImmediate() {
  16090. var instance = setImmediate.instance;
  16091. var root$$1 = instance.root;
  16092. var doc = root$$1.document;
  16093. var html = doc.documentElement;
  16094. var handle = instance.addFromSetImmediateArguments(arguments);
  16095. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  16096. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  16097. var script = doc.createElement('script');
  16098. script.onreadystatechange = function () {
  16099. instance.runIfPresent(handle);
  16100. script.onreadystatechange = null;
  16101. html.removeChild(script);
  16102. script = null;
  16103. };
  16104. html.appendChild(script);
  16105. return handle;
  16106. };
  16107. fn.instance = this;
  16108. return fn;
  16109. };
  16110. ImmediateDefinition.prototype.createSetTimeoutSetImmediate = function () {
  16111. var fn = function setImmediate() {
  16112. var instance = setImmediate.instance;
  16113. var handle = instance.addFromSetImmediateArguments(arguments);
  16114. instance.root.setTimeout(instance.partiallyApplied(instance.runIfPresent, handle), 0);
  16115. return handle;
  16116. };
  16117. fn.instance = this;
  16118. return fn;
  16119. };
  16120. return ImmediateDefinition;
  16121. }());
  16122. var Immediate = new ImmediateDefinition(_root);
  16123. /**
  16124. * We need this JSDoc comment for affecting ESDoc.
  16125. * @ignore
  16126. * @extends {Ignored}
  16127. */
  16128. var AsapAction = (function (_super) {
  16129. __extends(AsapAction, _super);
  16130. function AsapAction(scheduler, work) {
  16131. _super.call(this, scheduler, work);
  16132. this.scheduler = scheduler;
  16133. this.work = work;
  16134. }
  16135. AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
  16136. if (delay === void 0) { delay = 0; }
  16137. // If delay is greater than 0, request as an async action.
  16138. if (delay !== null && delay > 0) {
  16139. return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
  16140. }
  16141. // Push the action to the end of the scheduler queue.
  16142. scheduler.actions.push(this);
  16143. // If a microtask has already been scheduled, don't schedule another
  16144. // one. If a microtask hasn't been scheduled yet, schedule one now. Return
  16145. // the current scheduled microtask id.
  16146. return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(scheduler.flush.bind(scheduler, null)));
  16147. };
  16148. AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
  16149. if (delay === void 0) { delay = 0; }
  16150. // If delay exists and is greater than 0, or if the delay is null (the
  16151. // action wasn't rescheduled) but was originally scheduled as an async
  16152. // action, then recycle as an async action.
  16153. if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
  16154. return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
  16155. }
  16156. // If the scheduler queue is empty, cancel the requested microtask and
  16157. // set the scheduled flag to undefined so the next AsapAction will schedule
  16158. // its own.
  16159. if (scheduler.actions.length === 0) {
  16160. Immediate.clearImmediate(id);
  16161. scheduler.scheduled = undefined;
  16162. }
  16163. // Return undefined so the action knows to request a new async id if it's rescheduled.
  16164. return undefined;
  16165. };
  16166. return AsapAction;
  16167. }(AsyncAction));
  16168. var AsapScheduler = (function (_super) {
  16169. __extends(AsapScheduler, _super);
  16170. function AsapScheduler() {
  16171. _super.apply(this, arguments);
  16172. }
  16173. AsapScheduler.prototype.flush = function (action) {
  16174. this.active = true;
  16175. this.scheduled = undefined;
  16176. var actions = this.actions;
  16177. var error;
  16178. var index = -1;
  16179. var count = actions.length;
  16180. action = action || actions.shift();
  16181. do {
  16182. if (error = action.execute(action.state, action.delay)) {
  16183. break;
  16184. }
  16185. } while (++index < count && (action = actions.shift()));
  16186. this.active = false;
  16187. if (error) {
  16188. while (++index < count && (action = actions.shift())) {
  16189. action.unsubscribe();
  16190. }
  16191. throw error;
  16192. }
  16193. };
  16194. return AsapScheduler;
  16195. }(AsyncScheduler));
  16196. /**
  16197. *
  16198. * Asap Scheduler
  16199. *
  16200. * <span class="informal">Perform task as fast as it can be performed asynchronously</span>
  16201. *
  16202. * `asap` scheduler behaves the same as {@link async} scheduler when you use it to delay task
  16203. * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing
  16204. * code to end and then it will try to execute given task as fast as possible.
  16205. *
  16206. * `asap` scheduler will do its best to minimize time between end of currently executing code
  16207. * and start of scheduled task. This makes it best candidate for performing so called "deferring".
  16208. * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves
  16209. * some (although minimal) unwanted delay.
  16210. *
  16211. * Note that using `asap` scheduler does not necessarily mean that your task will be first to process
  16212. * after currently executing code. In particular, if some task was also scheduled with `asap` before,
  16213. * that task will execute first. That being said, if you need to schedule task asynchronously, but
  16214. * as soon as possible, `asap` scheduler is your best bet.
  16215. *
  16216. * @example <caption>Compare async and asap scheduler</caption>
  16217. *
  16218. * Rx.Scheduler.async.schedule(() => console.log('async')); // scheduling 'async' first...
  16219. * Rx.Scheduler.asap.schedule(() => console.log('asap'));
  16220. *
  16221. * // Logs:
  16222. * // "asap"
  16223. * // "async"
  16224. * // ... but 'asap' goes first!
  16225. *
  16226. * @static true
  16227. * @name asap
  16228. * @owner Scheduler
  16229. */
  16230. var asap = new AsapScheduler(AsapAction);
  16231. /**
  16232. * We need this JSDoc comment for affecting ESDoc.
  16233. * @extends {Ignored}
  16234. * @hide true
  16235. */
  16236. var SubscribeOnObservable = (function (_super) {
  16237. __extends(SubscribeOnObservable, _super);
  16238. function SubscribeOnObservable(source, delayTime, scheduler) {
  16239. if (delayTime === void 0) { delayTime = 0; }
  16240. if (scheduler === void 0) { scheduler = asap; }
  16241. _super.call(this);
  16242. this.source = source;
  16243. this.delayTime = delayTime;
  16244. this.scheduler = scheduler;
  16245. if (!isNumeric(delayTime) || delayTime < 0) {
  16246. this.delayTime = 0;
  16247. }
  16248. if (!scheduler || typeof scheduler.schedule !== 'function') {
  16249. this.scheduler = asap;
  16250. }
  16251. }
  16252. SubscribeOnObservable.create = function (source, delay, scheduler) {
  16253. if (delay === void 0) { delay = 0; }
  16254. if (scheduler === void 0) { scheduler = asap; }
  16255. return new SubscribeOnObservable(source, delay, scheduler);
  16256. };
  16257. SubscribeOnObservable.dispatch = function (arg) {
  16258. var source = arg.source, subscriber = arg.subscriber;
  16259. return this.add(source.subscribe(subscriber));
  16260. };
  16261. /** @deprecated internal use only */ SubscribeOnObservable.prototype._subscribe = function (subscriber) {
  16262. var delay = this.delayTime;
  16263. var source = this.source;
  16264. var scheduler = this.scheduler;
  16265. return scheduler.schedule(SubscribeOnObservable.dispatch, delay, {
  16266. source: source, subscriber: subscriber
  16267. });
  16268. };
  16269. return SubscribeOnObservable;
  16270. }(Observable));
  16271. /**
  16272. * Asynchronously subscribes Observers to this Observable on the specified IScheduler.
  16273. *
  16274. * <img src="./img/subscribeOn.png" width="100%">
  16275. *
  16276. * @param {Scheduler} scheduler - The IScheduler to perform subscription actions on.
  16277. * @return {Observable<T>} The source Observable modified so that its subscriptions happen on the specified IScheduler.
  16278. .
  16279. * @method subscribeOn
  16280. * @owner Observable
  16281. */
  16282. function subscribeOn$1(scheduler, delay) {
  16283. if (delay === void 0) { delay = 0; }
  16284. return function subscribeOnOperatorFunction(source) {
  16285. return source.lift(new SubscribeOnOperator(scheduler, delay));
  16286. };
  16287. }
  16288. var SubscribeOnOperator = (function () {
  16289. function SubscribeOnOperator(scheduler, delay) {
  16290. this.scheduler = scheduler;
  16291. this.delay = delay;
  16292. }
  16293. SubscribeOnOperator.prototype.call = function (subscriber, source) {
  16294. return new SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber);
  16295. };
  16296. return SubscribeOnOperator;
  16297. }());
  16298. /**
  16299. * Asynchronously subscribes Observers to this Observable on the specified IScheduler.
  16300. *
  16301. * <img src="./img/subscribeOn.png" width="100%">
  16302. *
  16303. * @param {Scheduler} scheduler - The IScheduler to perform subscription actions on.
  16304. * @return {Observable<T>} The source Observable modified so that its subscriptions happen on the specified IScheduler.
  16305. .
  16306. * @method subscribeOn
  16307. * @owner Observable
  16308. */
  16309. function subscribeOn$$1(scheduler, delay) {
  16310. if (delay === void 0) { delay = 0; }
  16311. return subscribeOn$1(scheduler, delay)(this);
  16312. }
  16313. Observable.prototype.subscribeOn = subscribeOn$$1;
  16314. /* tslint:enable:max-line-length */
  16315. /**
  16316. * Projects each source value to an Observable which is merged in the output
  16317. * Observable, emitting values only from the most recently projected Observable.
  16318. *
  16319. * <span class="informal">Maps each value to an Observable, then flattens all of
  16320. * these inner Observables using {@link switch}.</span>
  16321. *
  16322. * <img src="./img/switchMap.png" width="100%">
  16323. *
  16324. * Returns an Observable that emits items based on applying a function that you
  16325. * supply to each item emitted by the source Observable, where that function
  16326. * returns an (so-called "inner") Observable. Each time it observes one of these
  16327. * inner Observables, the output Observable begins emitting the items emitted by
  16328. * that inner Observable. When a new inner Observable is emitted, `switchMap`
  16329. * stops emitting items from the earlier-emitted inner Observable and begins
  16330. * emitting items from the new one. It continues to behave like this for
  16331. * subsequent inner Observables.
  16332. *
  16333. * @example <caption>Rerun an interval Observable on every click event</caption>
  16334. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16335. * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
  16336. * result.subscribe(x => console.log(x));
  16337. *
  16338. * @see {@link concatMap}
  16339. * @see {@link exhaustMap}
  16340. * @see {@link mergeMap}
  16341. * @see {@link switch}
  16342. * @see {@link switchMapTo}
  16343. *
  16344. * @param {function(value: T, ?index: number): ObservableInput} project A function
  16345. * that, when applied to an item emitted by the source Observable, returns an
  16346. * Observable.
  16347. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  16348. * A function to produce the value on the output Observable based on the values
  16349. * and the indices of the source (outer) emission and the inner Observable
  16350. * emission. The arguments passed to this function are:
  16351. * - `outerValue`: the value that came from the source
  16352. * - `innerValue`: the value that came from the projected Observable
  16353. * - `outerIndex`: the "index" of the value that came from the source
  16354. * - `innerIndex`: the "index" of the value from the projected Observable
  16355. * @return {Observable} An Observable that emits the result of applying the
  16356. * projection function (and the optional `resultSelector`) to each item emitted
  16357. * by the source Observable and taking only the values from the most recently
  16358. * projected inner Observable.
  16359. * @method switchMap
  16360. * @owner Observable
  16361. */
  16362. function switchMap(project, resultSelector) {
  16363. return function switchMapOperatorFunction(source) {
  16364. return source.lift(new SwitchMapOperator(project, resultSelector));
  16365. };
  16366. }
  16367. var SwitchMapOperator = (function () {
  16368. function SwitchMapOperator(project, resultSelector) {
  16369. this.project = project;
  16370. this.resultSelector = resultSelector;
  16371. }
  16372. SwitchMapOperator.prototype.call = function (subscriber, source) {
  16373. return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
  16374. };
  16375. return SwitchMapOperator;
  16376. }());
  16377. /**
  16378. * We need this JSDoc comment for affecting ESDoc.
  16379. * @ignore
  16380. * @extends {Ignored}
  16381. */
  16382. var SwitchMapSubscriber = (function (_super) {
  16383. __extends(SwitchMapSubscriber, _super);
  16384. function SwitchMapSubscriber(destination, project, resultSelector) {
  16385. _super.call(this, destination);
  16386. this.project = project;
  16387. this.resultSelector = resultSelector;
  16388. this.index = 0;
  16389. }
  16390. SwitchMapSubscriber.prototype._next = function (value) {
  16391. var result;
  16392. var index = this.index++;
  16393. try {
  16394. result = this.project(value, index);
  16395. }
  16396. catch (error) {
  16397. this.destination.error(error);
  16398. return;
  16399. }
  16400. this._innerSub(result, value, index);
  16401. };
  16402. SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
  16403. var innerSubscription = this.innerSubscription;
  16404. if (innerSubscription) {
  16405. innerSubscription.unsubscribe();
  16406. }
  16407. this.add(this.innerSubscription = subscribeToResult(this, result, value, index));
  16408. };
  16409. SwitchMapSubscriber.prototype._complete = function () {
  16410. var innerSubscription = this.innerSubscription;
  16411. if (!innerSubscription || innerSubscription.closed) {
  16412. _super.prototype._complete.call(this);
  16413. }
  16414. };
  16415. /** @deprecated internal use only */ SwitchMapSubscriber.prototype._unsubscribe = function () {
  16416. this.innerSubscription = null;
  16417. };
  16418. SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
  16419. this.remove(innerSub);
  16420. this.innerSubscription = null;
  16421. if (this.isStopped) {
  16422. _super.prototype._complete.call(this);
  16423. }
  16424. };
  16425. SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  16426. if (this.resultSelector) {
  16427. this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
  16428. }
  16429. else {
  16430. this.destination.next(innerValue);
  16431. }
  16432. };
  16433. SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
  16434. var result;
  16435. try {
  16436. result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
  16437. }
  16438. catch (err) {
  16439. this.destination.error(err);
  16440. return;
  16441. }
  16442. this.destination.next(result);
  16443. };
  16444. return SwitchMapSubscriber;
  16445. }(OuterSubscriber));
  16446. function switchAll() {
  16447. return switchMap(identity);
  16448. }
  16449. /**
  16450. * Converts a higher-order Observable into a first-order Observable by
  16451. * subscribing to only the most recently emitted of those inner Observables.
  16452. *
  16453. * <span class="informal">Flattens an Observable-of-Observables by dropping the
  16454. * previous inner Observable once a new one appears.</span>
  16455. *
  16456. * <img src="./img/switch.png" width="100%">
  16457. *
  16458. * `switch` subscribes to an Observable that emits Observables, also known as a
  16459. * higher-order Observable. Each time it observes one of these emitted inner
  16460. * Observables, the output Observable subscribes to the inner Observable and
  16461. * begins emitting the items emitted by that. So far, it behaves
  16462. * like {@link mergeAll}. However, when a new inner Observable is emitted,
  16463. * `switch` unsubscribes from the earlier-emitted inner Observable and
  16464. * subscribes to the new inner Observable and begins emitting items from it. It
  16465. * continues to behave like this for subsequent inner Observables.
  16466. *
  16467. * @example <caption>Rerun an interval Observable on every click event</caption>
  16468. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16469. * // Each click event is mapped to an Observable that ticks every second
  16470. * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
  16471. * var switched = higherOrder.switch();
  16472. * // The outcome is that `switched` is essentially a timer that restarts
  16473. * // on every click. The interval Observables from older clicks do not merge
  16474. * // with the current interval Observable.
  16475. * switched.subscribe(x => console.log(x));
  16476. *
  16477. * @see {@link combineAll}
  16478. * @see {@link concatAll}
  16479. * @see {@link exhaust}
  16480. * @see {@link mergeAll}
  16481. * @see {@link switchMap}
  16482. * @see {@link switchMapTo}
  16483. * @see {@link zipAll}
  16484. *
  16485. * @return {Observable<T>} An Observable that emits the items emitted by the
  16486. * Observable most recently emitted by the source Observable.
  16487. * @method switch
  16488. * @name switch
  16489. * @owner Observable
  16490. */
  16491. function _switch() {
  16492. return switchAll()(this);
  16493. }
  16494. Observable.prototype.switch = _switch;
  16495. Observable.prototype._switch = _switch;
  16496. /* tslint:enable:max-line-length */
  16497. /**
  16498. * Projects each source value to an Observable which is merged in the output
  16499. * Observable, emitting values only from the most recently projected Observable.
  16500. *
  16501. * <span class="informal">Maps each value to an Observable, then flattens all of
  16502. * these inner Observables using {@link switch}.</span>
  16503. *
  16504. * <img src="./img/switchMap.png" width="100%">
  16505. *
  16506. * Returns an Observable that emits items based on applying a function that you
  16507. * supply to each item emitted by the source Observable, where that function
  16508. * returns an (so-called "inner") Observable. Each time it observes one of these
  16509. * inner Observables, the output Observable begins emitting the items emitted by
  16510. * that inner Observable. When a new inner Observable is emitted, `switchMap`
  16511. * stops emitting items from the earlier-emitted inner Observable and begins
  16512. * emitting items from the new one. It continues to behave like this for
  16513. * subsequent inner Observables.
  16514. *
  16515. * @example <caption>Rerun an interval Observable on every click event</caption>
  16516. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16517. * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
  16518. * result.subscribe(x => console.log(x));
  16519. *
  16520. * @see {@link concatMap}
  16521. * @see {@link exhaustMap}
  16522. * @see {@link mergeMap}
  16523. * @see {@link switch}
  16524. * @see {@link switchMapTo}
  16525. *
  16526. * @param {function(value: T, ?index: number): ObservableInput} project A function
  16527. * that, when applied to an item emitted by the source Observable, returns an
  16528. * Observable.
  16529. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  16530. * A function to produce the value on the output Observable based on the values
  16531. * and the indices of the source (outer) emission and the inner Observable
  16532. * emission. The arguments passed to this function are:
  16533. * - `outerValue`: the value that came from the source
  16534. * - `innerValue`: the value that came from the projected Observable
  16535. * - `outerIndex`: the "index" of the value that came from the source
  16536. * - `innerIndex`: the "index" of the value from the projected Observable
  16537. * @return {Observable} An Observable that emits the result of applying the
  16538. * projection function (and the optional `resultSelector`) to each item emitted
  16539. * by the source Observable and taking only the values from the most recently
  16540. * projected inner Observable.
  16541. * @method switchMap
  16542. * @owner Observable
  16543. */
  16544. function switchMap$1(project, resultSelector) {
  16545. return switchMap(project, resultSelector)(this);
  16546. }
  16547. Observable.prototype.switchMap = switchMap$1;
  16548. /* tslint:enable:max-line-length */
  16549. /**
  16550. * Projects each source value to the same Observable which is flattened multiple
  16551. * times with {@link switch} in the output Observable.
  16552. *
  16553. * <span class="informal">It's like {@link switchMap}, but maps each value
  16554. * always to the same inner Observable.</span>
  16555. *
  16556. * <img src="./img/switchMapTo.png" width="100%">
  16557. *
  16558. * Maps each source value to the given Observable `innerObservable` regardless
  16559. * of the source value, and then flattens those resulting Observables into one
  16560. * single Observable, which is the output Observable. The output Observables
  16561. * emits values only from the most recently emitted instance of
  16562. * `innerObservable`.
  16563. *
  16564. * @example <caption>Rerun an interval Observable on every click event</caption>
  16565. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16566. * var result = clicks.switchMapTo(Rx.Observable.interval(1000));
  16567. * result.subscribe(x => console.log(x));
  16568. *
  16569. * @see {@link concatMapTo}
  16570. * @see {@link switch}
  16571. * @see {@link switchMap}
  16572. * @see {@link mergeMapTo}
  16573. *
  16574. * @param {ObservableInput} innerObservable An Observable to replace each value from
  16575. * the source Observable.
  16576. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  16577. * A function to produce the value on the output Observable based on the values
  16578. * and the indices of the source (outer) emission and the inner Observable
  16579. * emission. The arguments passed to this function are:
  16580. * - `outerValue`: the value that came from the source
  16581. * - `innerValue`: the value that came from the projected Observable
  16582. * - `outerIndex`: the "index" of the value that came from the source
  16583. * - `innerIndex`: the "index" of the value from the projected Observable
  16584. * @return {Observable} An Observable that emits items from the given
  16585. * `innerObservable` (and optionally transformed through `resultSelector`) every
  16586. * time a value is emitted on the source Observable, and taking only the values
  16587. * from the most recently projected inner Observable.
  16588. * @method switchMapTo
  16589. * @owner Observable
  16590. */
  16591. function switchMapTo$1(innerObservable, resultSelector) {
  16592. return function (source) { return source.lift(new SwitchMapToOperator(innerObservable, resultSelector)); };
  16593. }
  16594. var SwitchMapToOperator = (function () {
  16595. function SwitchMapToOperator(observable, resultSelector) {
  16596. this.observable = observable;
  16597. this.resultSelector = resultSelector;
  16598. }
  16599. SwitchMapToOperator.prototype.call = function (subscriber, source) {
  16600. return source.subscribe(new SwitchMapToSubscriber(subscriber, this.observable, this.resultSelector));
  16601. };
  16602. return SwitchMapToOperator;
  16603. }());
  16604. /**
  16605. * We need this JSDoc comment for affecting ESDoc.
  16606. * @ignore
  16607. * @extends {Ignored}
  16608. */
  16609. var SwitchMapToSubscriber = (function (_super) {
  16610. __extends(SwitchMapToSubscriber, _super);
  16611. function SwitchMapToSubscriber(destination, inner, resultSelector) {
  16612. _super.call(this, destination);
  16613. this.inner = inner;
  16614. this.resultSelector = resultSelector;
  16615. this.index = 0;
  16616. }
  16617. SwitchMapToSubscriber.prototype._next = function (value) {
  16618. var innerSubscription = this.innerSubscription;
  16619. if (innerSubscription) {
  16620. innerSubscription.unsubscribe();
  16621. }
  16622. this.add(this.innerSubscription = subscribeToResult(this, this.inner, value, this.index++));
  16623. };
  16624. SwitchMapToSubscriber.prototype._complete = function () {
  16625. var innerSubscription = this.innerSubscription;
  16626. if (!innerSubscription || innerSubscription.closed) {
  16627. _super.prototype._complete.call(this);
  16628. }
  16629. };
  16630. /** @deprecated internal use only */ SwitchMapToSubscriber.prototype._unsubscribe = function () {
  16631. this.innerSubscription = null;
  16632. };
  16633. SwitchMapToSubscriber.prototype.notifyComplete = function (innerSub) {
  16634. this.remove(innerSub);
  16635. this.innerSubscription = null;
  16636. if (this.isStopped) {
  16637. _super.prototype._complete.call(this);
  16638. }
  16639. };
  16640. SwitchMapToSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  16641. var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
  16642. if (resultSelector) {
  16643. this.tryResultSelector(outerValue, innerValue, outerIndex, innerIndex);
  16644. }
  16645. else {
  16646. destination.next(innerValue);
  16647. }
  16648. };
  16649. SwitchMapToSubscriber.prototype.tryResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
  16650. var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
  16651. var result;
  16652. try {
  16653. result = resultSelector(outerValue, innerValue, outerIndex, innerIndex);
  16654. }
  16655. catch (err) {
  16656. destination.error(err);
  16657. return;
  16658. }
  16659. destination.next(result);
  16660. };
  16661. return SwitchMapToSubscriber;
  16662. }(OuterSubscriber));
  16663. /* tslint:enable:max-line-length */
  16664. /**
  16665. * Projects each source value to the same Observable which is flattened multiple
  16666. * times with {@link switch} in the output Observable.
  16667. *
  16668. * <span class="informal">It's like {@link switchMap}, but maps each value
  16669. * always to the same inner Observable.</span>
  16670. *
  16671. * <img src="./img/switchMapTo.png" width="100%">
  16672. *
  16673. * Maps each source value to the given Observable `innerObservable` regardless
  16674. * of the source value, and then flattens those resulting Observables into one
  16675. * single Observable, which is the output Observable. The output Observables
  16676. * emits values only from the most recently emitted instance of
  16677. * `innerObservable`.
  16678. *
  16679. * @example <caption>Rerun an interval Observable on every click event</caption>
  16680. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16681. * var result = clicks.switchMapTo(Rx.Observable.interval(1000));
  16682. * result.subscribe(x => console.log(x));
  16683. *
  16684. * @see {@link concatMapTo}
  16685. * @see {@link switch}
  16686. * @see {@link switchMap}
  16687. * @see {@link mergeMapTo}
  16688. *
  16689. * @param {ObservableInput} innerObservable An Observable to replace each value from
  16690. * the source Observable.
  16691. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
  16692. * A function to produce the value on the output Observable based on the values
  16693. * and the indices of the source (outer) emission and the inner Observable
  16694. * emission. The arguments passed to this function are:
  16695. * - `outerValue`: the value that came from the source
  16696. * - `innerValue`: the value that came from the projected Observable
  16697. * - `outerIndex`: the "index" of the value that came from the source
  16698. * - `innerIndex`: the "index" of the value from the projected Observable
  16699. * @return {Observable} An Observable that emits items from the given
  16700. * `innerObservable` (and optionally transformed through `resultSelector`) every
  16701. * time a value is emitted on the source Observable, and taking only the values
  16702. * from the most recently projected inner Observable.
  16703. * @method switchMapTo
  16704. * @owner Observable
  16705. */
  16706. function switchMapTo$$1(innerObservable, resultSelector) {
  16707. return switchMapTo$1(innerObservable, resultSelector)(this);
  16708. }
  16709. Observable.prototype.switchMapTo = switchMapTo$$1;
  16710. /**
  16711. * Emits only the first `count` values emitted by the source Observable.
  16712. *
  16713. * <span class="informal">Takes the first `count` values from the source, then
  16714. * completes.</span>
  16715. *
  16716. * <img src="./img/take.png" width="100%">
  16717. *
  16718. * `take` returns an Observable that emits only the first `count` values emitted
  16719. * by the source Observable. If the source emits fewer than `count` values then
  16720. * all of its values are emitted. After that, it completes, regardless if the
  16721. * source completes.
  16722. *
  16723. * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
  16724. * var interval = Rx.Observable.interval(1000);
  16725. * var five = interval.take(5);
  16726. * five.subscribe(x => console.log(x));
  16727. *
  16728. * @see {@link takeLast}
  16729. * @see {@link takeUntil}
  16730. * @see {@link takeWhile}
  16731. * @see {@link skip}
  16732. *
  16733. * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
  16734. * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
  16735. *
  16736. * @param {number} count The maximum number of `next` values to emit.
  16737. * @return {Observable<T>} An Observable that emits only the first `count`
  16738. * values emitted by the source Observable, or all of the values from the source
  16739. * if the source emits fewer than `count` values.
  16740. * @method take
  16741. * @owner Observable
  16742. */
  16743. function take$1(count) {
  16744. return function (source) {
  16745. if (count === 0) {
  16746. return new EmptyObservable();
  16747. }
  16748. else {
  16749. return source.lift(new TakeOperator(count));
  16750. }
  16751. };
  16752. }
  16753. var TakeOperator = (function () {
  16754. function TakeOperator(total) {
  16755. this.total = total;
  16756. if (this.total < 0) {
  16757. throw new ArgumentOutOfRangeError;
  16758. }
  16759. }
  16760. TakeOperator.prototype.call = function (subscriber, source) {
  16761. return source.subscribe(new TakeSubscriber(subscriber, this.total));
  16762. };
  16763. return TakeOperator;
  16764. }());
  16765. /**
  16766. * We need this JSDoc comment for affecting ESDoc.
  16767. * @ignore
  16768. * @extends {Ignored}
  16769. */
  16770. var TakeSubscriber = (function (_super) {
  16771. __extends(TakeSubscriber, _super);
  16772. function TakeSubscriber(destination, total) {
  16773. _super.call(this, destination);
  16774. this.total = total;
  16775. this.count = 0;
  16776. }
  16777. TakeSubscriber.prototype._next = function (value) {
  16778. var total = this.total;
  16779. var count = ++this.count;
  16780. if (count <= total) {
  16781. this.destination.next(value);
  16782. if (count === total) {
  16783. this.destination.complete();
  16784. this.unsubscribe();
  16785. }
  16786. }
  16787. };
  16788. return TakeSubscriber;
  16789. }(Subscriber));
  16790. /**
  16791. * Emits only the first `count` values emitted by the source Observable.
  16792. *
  16793. * <span class="informal">Takes the first `count` values from the source, then
  16794. * completes.</span>
  16795. *
  16796. * <img src="./img/take.png" width="100%">
  16797. *
  16798. * `take` returns an Observable that emits only the first `count` values emitted
  16799. * by the source Observable. If the source emits fewer than `count` values then
  16800. * all of its values are emitted. After that, it completes, regardless if the
  16801. * source completes.
  16802. *
  16803. * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
  16804. * var interval = Rx.Observable.interval(1000);
  16805. * var five = interval.take(5);
  16806. * five.subscribe(x => console.log(x));
  16807. *
  16808. * @see {@link takeLast}
  16809. * @see {@link takeUntil}
  16810. * @see {@link takeWhile}
  16811. * @see {@link skip}
  16812. *
  16813. * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
  16814. * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
  16815. *
  16816. * @param {number} count The maximum number of `next` values to emit.
  16817. * @return {Observable<T>} An Observable that emits only the first `count`
  16818. * values emitted by the source Observable, or all of the values from the source
  16819. * if the source emits fewer than `count` values.
  16820. * @method take
  16821. * @owner Observable
  16822. */
  16823. function take$$1(count) {
  16824. return take$1(count)(this);
  16825. }
  16826. Observable.prototype.take = take$$1;
  16827. /**
  16828. * Emits only the last `count` values emitted by the source Observable.
  16829. *
  16830. * <span class="informal">Remembers the latest `count` values, then emits those
  16831. * only when the source completes.</span>
  16832. *
  16833. * <img src="./img/takeLast.png" width="100%">
  16834. *
  16835. * `takeLast` returns an Observable that emits at most the last `count` values
  16836. * emitted by the source Observable. If the source emits fewer than `count`
  16837. * values then all of its values are emitted. This operator must wait until the
  16838. * `complete` notification emission from the source in order to emit the `next`
  16839. * values on the output Observable, because otherwise it is impossible to know
  16840. * whether or not more values will be emitted on the source. For this reason,
  16841. * all values are emitted synchronously, followed by the complete notification.
  16842. *
  16843. * @example <caption>Take the last 3 values of an Observable with many values</caption>
  16844. * var many = Rx.Observable.range(1, 100);
  16845. * var lastThree = many.takeLast(3);
  16846. * lastThree.subscribe(x => console.log(x));
  16847. *
  16848. * @see {@link take}
  16849. * @see {@link takeUntil}
  16850. * @see {@link takeWhile}
  16851. * @see {@link skip}
  16852. *
  16853. * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an
  16854. * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
  16855. *
  16856. * @param {number} count The maximum number of values to emit from the end of
  16857. * the sequence of values emitted by the source Observable.
  16858. * @return {Observable<T>} An Observable that emits at most the last count
  16859. * values emitted by the source Observable.
  16860. * @method takeLast
  16861. * @owner Observable
  16862. */
  16863. function takeLast$1(count) {
  16864. return takeLast(count)(this);
  16865. }
  16866. Observable.prototype.takeLast = takeLast$1;
  16867. /**
  16868. * Emits the values emitted by the source Observable until a `notifier`
  16869. * Observable emits a value.
  16870. *
  16871. * <span class="informal">Lets values pass until a second Observable,
  16872. * `notifier`, emits something. Then, it completes.</span>
  16873. *
  16874. * <img src="./img/takeUntil.png" width="100%">
  16875. *
  16876. * `takeUntil` subscribes and begins mirroring the source Observable. It also
  16877. * monitors a second Observable, `notifier` that you provide. If the `notifier`
  16878. * emits a value or a complete notification, the output Observable stops
  16879. * mirroring the source Observable and completes.
  16880. *
  16881. * @example <caption>Tick every second until the first click happens</caption>
  16882. * var interval = Rx.Observable.interval(1000);
  16883. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16884. * var result = interval.takeUntil(clicks);
  16885. * result.subscribe(x => console.log(x));
  16886. *
  16887. * @see {@link take}
  16888. * @see {@link takeLast}
  16889. * @see {@link takeWhile}
  16890. * @see {@link skip}
  16891. *
  16892. * @param {Observable} notifier The Observable whose first emitted value will
  16893. * cause the output Observable of `takeUntil` to stop emitting values from the
  16894. * source Observable.
  16895. * @return {Observable<T>} An Observable that emits the values from the source
  16896. * Observable until such time as `notifier` emits its first value.
  16897. * @method takeUntil
  16898. * @owner Observable
  16899. */
  16900. function takeUntil$1(notifier) {
  16901. return function (source) { return source.lift(new TakeUntilOperator(notifier)); };
  16902. }
  16903. var TakeUntilOperator = (function () {
  16904. function TakeUntilOperator(notifier) {
  16905. this.notifier = notifier;
  16906. }
  16907. TakeUntilOperator.prototype.call = function (subscriber, source) {
  16908. return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
  16909. };
  16910. return TakeUntilOperator;
  16911. }());
  16912. /**
  16913. * We need this JSDoc comment for affecting ESDoc.
  16914. * @ignore
  16915. * @extends {Ignored}
  16916. */
  16917. var TakeUntilSubscriber = (function (_super) {
  16918. __extends(TakeUntilSubscriber, _super);
  16919. function TakeUntilSubscriber(destination, notifier) {
  16920. _super.call(this, destination);
  16921. this.notifier = notifier;
  16922. this.add(subscribeToResult(this, notifier));
  16923. }
  16924. TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  16925. this.complete();
  16926. };
  16927. TakeUntilSubscriber.prototype.notifyComplete = function () {
  16928. // noop
  16929. };
  16930. return TakeUntilSubscriber;
  16931. }(OuterSubscriber));
  16932. /**
  16933. * Emits the values emitted by the source Observable until a `notifier`
  16934. * Observable emits a value.
  16935. *
  16936. * <span class="informal">Lets values pass until a second Observable,
  16937. * `notifier`, emits something. Then, it completes.</span>
  16938. *
  16939. * <img src="./img/takeUntil.png" width="100%">
  16940. *
  16941. * `takeUntil` subscribes and begins mirroring the source Observable. It also
  16942. * monitors a second Observable, `notifier` that you provide. If the `notifier`
  16943. * emits a value, the output Observable stops mirroring the source Observable
  16944. * and completes.
  16945. *
  16946. * @example <caption>Tick every second until the first click happens</caption>
  16947. * var interval = Rx.Observable.interval(1000);
  16948. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16949. * var result = interval.takeUntil(clicks);
  16950. * result.subscribe(x => console.log(x));
  16951. *
  16952. * @see {@link take}
  16953. * @see {@link takeLast}
  16954. * @see {@link takeWhile}
  16955. * @see {@link skip}
  16956. *
  16957. * @param {Observable} notifier The Observable whose first emitted value will
  16958. * cause the output Observable of `takeUntil` to stop emitting values from the
  16959. * source Observable.
  16960. * @return {Observable<T>} An Observable that emits the values from the source
  16961. * Observable until such time as `notifier` emits its first value.
  16962. * @method takeUntil
  16963. * @owner Observable
  16964. */
  16965. function takeUntil$$1(notifier) {
  16966. return takeUntil$1(notifier)(this);
  16967. }
  16968. Observable.prototype.takeUntil = takeUntil$$1;
  16969. /**
  16970. * Emits values emitted by the source Observable so long as each value satisfies
  16971. * the given `predicate`, and then completes as soon as this `predicate` is not
  16972. * satisfied.
  16973. *
  16974. * <span class="informal">Takes values from the source only while they pass the
  16975. * condition given. When the first value does not satisfy, it completes.</span>
  16976. *
  16977. * <img src="./img/takeWhile.png" width="100%">
  16978. *
  16979. * `takeWhile` subscribes and begins mirroring the source Observable. Each value
  16980. * emitted on the source is given to the `predicate` function which returns a
  16981. * boolean, representing a condition to be satisfied by the source values. The
  16982. * output Observable emits the source values until such time as the `predicate`
  16983. * returns false, at which point `takeWhile` stops mirroring the source
  16984. * Observable and completes the output Observable.
  16985. *
  16986. * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
  16987. * var clicks = Rx.Observable.fromEvent(document, 'click');
  16988. * var result = clicks.takeWhile(ev => ev.clientX > 200);
  16989. * result.subscribe(x => console.log(x));
  16990. *
  16991. * @see {@link take}
  16992. * @see {@link takeLast}
  16993. * @see {@link takeUntil}
  16994. * @see {@link skip}
  16995. *
  16996. * @param {function(value: T, index: number): boolean} predicate A function that
  16997. * evaluates a value emitted by the source Observable and returns a boolean.
  16998. * Also takes the (zero-based) index as the second argument.
  16999. * @return {Observable<T>} An Observable that emits the values from the source
  17000. * Observable so long as each value satisfies the condition defined by the
  17001. * `predicate`, then completes.
  17002. * @method takeWhile
  17003. * @owner Observable
  17004. */
  17005. function takeWhile$1(predicate) {
  17006. return function (source) { return source.lift(new TakeWhileOperator(predicate)); };
  17007. }
  17008. var TakeWhileOperator = (function () {
  17009. function TakeWhileOperator(predicate) {
  17010. this.predicate = predicate;
  17011. }
  17012. TakeWhileOperator.prototype.call = function (subscriber, source) {
  17013. return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
  17014. };
  17015. return TakeWhileOperator;
  17016. }());
  17017. /**
  17018. * We need this JSDoc comment for affecting ESDoc.
  17019. * @ignore
  17020. * @extends {Ignored}
  17021. */
  17022. var TakeWhileSubscriber = (function (_super) {
  17023. __extends(TakeWhileSubscriber, _super);
  17024. function TakeWhileSubscriber(destination, predicate) {
  17025. _super.call(this, destination);
  17026. this.predicate = predicate;
  17027. this.index = 0;
  17028. }
  17029. TakeWhileSubscriber.prototype._next = function (value) {
  17030. var destination = this.destination;
  17031. var result;
  17032. try {
  17033. result = this.predicate(value, this.index++);
  17034. }
  17035. catch (err) {
  17036. destination.error(err);
  17037. return;
  17038. }
  17039. this.nextOrComplete(value, result);
  17040. };
  17041. TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
  17042. var destination = this.destination;
  17043. if (Boolean(predicateResult)) {
  17044. destination.next(value);
  17045. }
  17046. else {
  17047. destination.complete();
  17048. }
  17049. };
  17050. return TakeWhileSubscriber;
  17051. }(Subscriber));
  17052. /**
  17053. * Emits values emitted by the source Observable so long as each value satisfies
  17054. * the given `predicate`, and then completes as soon as this `predicate` is not
  17055. * satisfied.
  17056. *
  17057. * <span class="informal">Takes values from the source only while they pass the
  17058. * condition given. When the first value does not satisfy, it completes.</span>
  17059. *
  17060. * <img src="./img/takeWhile.png" width="100%">
  17061. *
  17062. * `takeWhile` subscribes and begins mirroring the source Observable. Each value
  17063. * emitted on the source is given to the `predicate` function which returns a
  17064. * boolean, representing a condition to be satisfied by the source values. The
  17065. * output Observable emits the source values until such time as the `predicate`
  17066. * returns false, at which point `takeWhile` stops mirroring the source
  17067. * Observable and completes the output Observable.
  17068. *
  17069. * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
  17070. * var clicks = Rx.Observable.fromEvent(document, 'click');
  17071. * var result = clicks.takeWhile(ev => ev.clientX > 200);
  17072. * result.subscribe(x => console.log(x));
  17073. *
  17074. * @see {@link take}
  17075. * @see {@link takeLast}
  17076. * @see {@link takeUntil}
  17077. * @see {@link skip}
  17078. *
  17079. * @param {function(value: T, index: number): boolean} predicate A function that
  17080. * evaluates a value emitted by the source Observable and returns a boolean.
  17081. * Also takes the (zero-based) index as the second argument.
  17082. * @return {Observable<T>} An Observable that emits the values from the source
  17083. * Observable so long as each value satisfies the condition defined by the
  17084. * `predicate`, then completes.
  17085. * @method takeWhile
  17086. * @owner Observable
  17087. */
  17088. function takeWhile$$1(predicate) {
  17089. return takeWhile$1(predicate)(this);
  17090. }
  17091. Observable.prototype.takeWhile = takeWhile$$1;
  17092. var defaultThrottleConfig = {
  17093. leading: true,
  17094. trailing: false
  17095. };
  17096. /**
  17097. * Emits a value from the source Observable, then ignores subsequent source
  17098. * values for a duration determined by another Observable, then repeats this
  17099. * process.
  17100. *
  17101. * <span class="informal">It's like {@link throttleTime}, but the silencing
  17102. * duration is determined by a second Observable.</span>
  17103. *
  17104. * <img src="./img/throttle.png" width="100%">
  17105. *
  17106. * `throttle` emits the source Observable values on the output Observable
  17107. * when its internal timer is disabled, and ignores source values when the timer
  17108. * is enabled. Initially, the timer is disabled. As soon as the first source
  17109. * value arrives, it is forwarded to the output Observable, and then the timer
  17110. * is enabled by calling the `durationSelector` function with the source value,
  17111. * which returns the "duration" Observable. When the duration Observable emits a
  17112. * value or completes, the timer is disabled, and this process repeats for the
  17113. * next source value.
  17114. *
  17115. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  17116. * var clicks = Rx.Observable.fromEvent(document, 'click');
  17117. * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
  17118. * result.subscribe(x => console.log(x));
  17119. *
  17120. * @see {@link audit}
  17121. * @see {@link debounce}
  17122. * @see {@link delayWhen}
  17123. * @see {@link sample}
  17124. * @see {@link throttleTime}
  17125. *
  17126. * @param {function(value: T): SubscribableOrPromise} durationSelector A function
  17127. * that receives a value from the source Observable, for computing the silencing
  17128. * duration for each source value, returned as an Observable or a Promise.
  17129. * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
  17130. * to `{ leading: true, trailing: false }`.
  17131. * @return {Observable<T>} An Observable that performs the throttle operation to
  17132. * limit the rate of emissions from the source.
  17133. * @method throttle
  17134. * @owner Observable
  17135. */
  17136. function throttle$1(durationSelector, config) {
  17137. if (config === void 0) { config = defaultThrottleConfig; }
  17138. return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
  17139. }
  17140. var ThrottleOperator = (function () {
  17141. function ThrottleOperator(durationSelector, leading, trailing) {
  17142. this.durationSelector = durationSelector;
  17143. this.leading = leading;
  17144. this.trailing = trailing;
  17145. }
  17146. ThrottleOperator.prototype.call = function (subscriber, source) {
  17147. return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
  17148. };
  17149. return ThrottleOperator;
  17150. }());
  17151. /**
  17152. * We need this JSDoc comment for affecting ESDoc
  17153. * @ignore
  17154. * @extends {Ignored}
  17155. */
  17156. var ThrottleSubscriber = (function (_super) {
  17157. __extends(ThrottleSubscriber, _super);
  17158. function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
  17159. _super.call(this, destination);
  17160. this.destination = destination;
  17161. this.durationSelector = durationSelector;
  17162. this._leading = _leading;
  17163. this._trailing = _trailing;
  17164. this._hasTrailingValue = false;
  17165. }
  17166. ThrottleSubscriber.prototype._next = function (value) {
  17167. if (this.throttled) {
  17168. if (this._trailing) {
  17169. this._hasTrailingValue = true;
  17170. this._trailingValue = value;
  17171. }
  17172. }
  17173. else {
  17174. var duration = this.tryDurationSelector(value);
  17175. if (duration) {
  17176. this.add(this.throttled = subscribeToResult(this, duration));
  17177. }
  17178. if (this._leading) {
  17179. this.destination.next(value);
  17180. if (this._trailing) {
  17181. this._hasTrailingValue = true;
  17182. this._trailingValue = value;
  17183. }
  17184. }
  17185. }
  17186. };
  17187. ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
  17188. try {
  17189. return this.durationSelector(value);
  17190. }
  17191. catch (err) {
  17192. this.destination.error(err);
  17193. return null;
  17194. }
  17195. };
  17196. /** @deprecated internal use only */ ThrottleSubscriber.prototype._unsubscribe = function () {
  17197. var _a = this, throttled = _a.throttled, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue, _trailing = _a._trailing;
  17198. this._trailingValue = null;
  17199. this._hasTrailingValue = false;
  17200. if (throttled) {
  17201. this.remove(throttled);
  17202. this.throttled = null;
  17203. throttled.unsubscribe();
  17204. }
  17205. };
  17206. ThrottleSubscriber.prototype._sendTrailing = function () {
  17207. var _a = this, destination = _a.destination, throttled = _a.throttled, _trailing = _a._trailing, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue;
  17208. if (throttled && _trailing && _hasTrailingValue) {
  17209. destination.next(_trailingValue);
  17210. this._trailingValue = null;
  17211. this._hasTrailingValue = false;
  17212. }
  17213. };
  17214. ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  17215. this._sendTrailing();
  17216. this._unsubscribe();
  17217. };
  17218. ThrottleSubscriber.prototype.notifyComplete = function () {
  17219. this._sendTrailing();
  17220. this._unsubscribe();
  17221. };
  17222. return ThrottleSubscriber;
  17223. }(OuterSubscriber));
  17224. /**
  17225. * Emits a value from the source Observable, then ignores subsequent source
  17226. * values for a duration determined by another Observable, then repeats this
  17227. * process.
  17228. *
  17229. * <span class="informal">It's like {@link throttleTime}, but the silencing
  17230. * duration is determined by a second Observable.</span>
  17231. *
  17232. * <img src="./img/throttle.png" width="100%">
  17233. *
  17234. * `throttle` emits the source Observable values on the output Observable
  17235. * when its internal timer is disabled, and ignores source values when the timer
  17236. * is enabled. Initially, the timer is disabled. As soon as the first source
  17237. * value arrives, it is forwarded to the output Observable, and then the timer
  17238. * is enabled by calling the `durationSelector` function with the source value,
  17239. * which returns the "duration" Observable. When the duration Observable emits a
  17240. * value or completes, the timer is disabled, and this process repeats for the
  17241. * next source value.
  17242. *
  17243. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  17244. * var clicks = Rx.Observable.fromEvent(document, 'click');
  17245. * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
  17246. * result.subscribe(x => console.log(x));
  17247. *
  17248. * @see {@link audit}
  17249. * @see {@link debounce}
  17250. * @see {@link delayWhen}
  17251. * @see {@link sample}
  17252. * @see {@link throttleTime}
  17253. *
  17254. * @param {function(value: T): SubscribableOrPromise} durationSelector A function
  17255. * that receives a value from the source Observable, for computing the silencing
  17256. * duration for each source value, returned as an Observable or a Promise.
  17257. * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
  17258. * to `{ leading: true, trailing: false }`.
  17259. * @return {Observable<T>} An Observable that performs the throttle operation to
  17260. * limit the rate of emissions from the source.
  17261. * @method throttle
  17262. * @owner Observable
  17263. */
  17264. function throttle$$1(durationSelector, config) {
  17265. if (config === void 0) { config = defaultThrottleConfig; }
  17266. return throttle$1(durationSelector, config)(this);
  17267. }
  17268. Observable.prototype.throttle = throttle$$1;
  17269. /**
  17270. * Emits a value from the source Observable, then ignores subsequent source
  17271. * values for `duration` milliseconds, then repeats this process.
  17272. *
  17273. * <span class="informal">Lets a value pass, then ignores source values for the
  17274. * next `duration` milliseconds.</span>
  17275. *
  17276. * <img src="./img/throttleTime.png" width="100%">
  17277. *
  17278. * `throttleTime` emits the source Observable values on the output Observable
  17279. * when its internal timer is disabled, and ignores source values when the timer
  17280. * is enabled. Initially, the timer is disabled. As soon as the first source
  17281. * value arrives, it is forwarded to the output Observable, and then the timer
  17282. * is enabled. After `duration` milliseconds (or the time unit determined
  17283. * internally by the optional `scheduler`) has passed, the timer is disabled,
  17284. * and this process repeats for the next source value. Optionally takes a
  17285. * {@link IScheduler} for managing timers.
  17286. *
  17287. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  17288. * var clicks = Rx.Observable.fromEvent(document, 'click');
  17289. * var result = clicks.throttleTime(1000);
  17290. * result.subscribe(x => console.log(x));
  17291. *
  17292. * @see {@link auditTime}
  17293. * @see {@link debounceTime}
  17294. * @see {@link delay}
  17295. * @see {@link sampleTime}
  17296. * @see {@link throttle}
  17297. *
  17298. * @param {number} duration Time to wait before emitting another value after
  17299. * emitting the last value, measured in milliseconds or the time unit determined
  17300. * internally by the optional `scheduler`.
  17301. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  17302. * managing the timers that handle the throttling.
  17303. * @return {Observable<T>} An Observable that performs the throttle operation to
  17304. * limit the rate of emissions from the source.
  17305. * @method throttleTime
  17306. * @owner Observable
  17307. */
  17308. function throttleTime$1(duration, scheduler, config) {
  17309. if (scheduler === void 0) { scheduler = async; }
  17310. if (config === void 0) { config = defaultThrottleConfig; }
  17311. return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
  17312. }
  17313. var ThrottleTimeOperator = (function () {
  17314. function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
  17315. this.duration = duration;
  17316. this.scheduler = scheduler;
  17317. this.leading = leading;
  17318. this.trailing = trailing;
  17319. }
  17320. ThrottleTimeOperator.prototype.call = function (subscriber, source) {
  17321. return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
  17322. };
  17323. return ThrottleTimeOperator;
  17324. }());
  17325. /**
  17326. * We need this JSDoc comment for affecting ESDoc.
  17327. * @ignore
  17328. * @extends {Ignored}
  17329. */
  17330. var ThrottleTimeSubscriber = (function (_super) {
  17331. __extends(ThrottleTimeSubscriber, _super);
  17332. function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
  17333. _super.call(this, destination);
  17334. this.duration = duration;
  17335. this.scheduler = scheduler;
  17336. this.leading = leading;
  17337. this.trailing = trailing;
  17338. this._hasTrailingValue = false;
  17339. this._trailingValue = null;
  17340. }
  17341. ThrottleTimeSubscriber.prototype._next = function (value) {
  17342. if (this.throttled) {
  17343. if (this.trailing) {
  17344. this._trailingValue = value;
  17345. this._hasTrailingValue = true;
  17346. }
  17347. }
  17348. else {
  17349. this.add(this.throttled = this.scheduler.schedule(dispatchNext$4, this.duration, { subscriber: this }));
  17350. if (this.leading) {
  17351. this.destination.next(value);
  17352. }
  17353. }
  17354. };
  17355. ThrottleTimeSubscriber.prototype.clearThrottle = function () {
  17356. var throttled = this.throttled;
  17357. if (throttled) {
  17358. if (this.trailing && this._hasTrailingValue) {
  17359. this.destination.next(this._trailingValue);
  17360. this._trailingValue = null;
  17361. this._hasTrailingValue = false;
  17362. }
  17363. throttled.unsubscribe();
  17364. this.remove(throttled);
  17365. this.throttled = null;
  17366. }
  17367. };
  17368. return ThrottleTimeSubscriber;
  17369. }(Subscriber));
  17370. function dispatchNext$4(arg) {
  17371. var subscriber = arg.subscriber;
  17372. subscriber.clearThrottle();
  17373. }
  17374. /**
  17375. * Emits a value from the source Observable, then ignores subsequent source
  17376. * values for `duration` milliseconds, then repeats this process.
  17377. *
  17378. * <span class="informal">Lets a value pass, then ignores source values for the
  17379. * next `duration` milliseconds.</span>
  17380. *
  17381. * <img src="./img/throttleTime.png" width="100%">
  17382. *
  17383. * `throttleTime` emits the source Observable values on the output Observable
  17384. * when its internal timer is disabled, and ignores source values when the timer
  17385. * is enabled. Initially, the timer is disabled. As soon as the first source
  17386. * value arrives, it is forwarded to the output Observable, and then the timer
  17387. * is enabled. After `duration` milliseconds (or the time unit determined
  17388. * internally by the optional `scheduler`) has passed, the timer is disabled,
  17389. * and this process repeats for the next source value. Optionally takes a
  17390. * {@link IScheduler} for managing timers.
  17391. *
  17392. * @example <caption>Emit clicks at a rate of at most one click per second</caption>
  17393. * var clicks = Rx.Observable.fromEvent(document, 'click');
  17394. * var result = clicks.throttleTime(1000);
  17395. * result.subscribe(x => console.log(x));
  17396. *
  17397. * @see {@link auditTime}
  17398. * @see {@link debounceTime}
  17399. * @see {@link delay}
  17400. * @see {@link sampleTime}
  17401. * @see {@link throttle}
  17402. *
  17403. * @param {number} duration Time to wait before emitting another value after
  17404. * emitting the last value, measured in milliseconds or the time unit determined
  17405. * internally by the optional `scheduler`.
  17406. * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
  17407. * managing the timers that handle the throttling.
  17408. * @return {Observable<T>} An Observable that performs the throttle operation to
  17409. * limit the rate of emissions from the source.
  17410. * @method throttleTime
  17411. * @owner Observable
  17412. */
  17413. function throttleTime$$1(duration, scheduler, config) {
  17414. if (scheduler === void 0) { scheduler = async; }
  17415. if (config === void 0) { config = defaultThrottleConfig; }
  17416. return throttleTime$1(duration, scheduler, config)(this);
  17417. }
  17418. Observable.prototype.throttleTime = throttleTime$$1;
  17419. function timeInterval$1(scheduler) {
  17420. if (scheduler === void 0) { scheduler = async; }
  17421. return function (source) { return source.lift(new TimeIntervalOperator(scheduler)); };
  17422. }
  17423. var TimeInterval = (function () {
  17424. function TimeInterval(value, interval) {
  17425. this.value = value;
  17426. this.interval = interval;
  17427. }
  17428. return TimeInterval;
  17429. }());
  17430. var TimeIntervalOperator = (function () {
  17431. function TimeIntervalOperator(scheduler) {
  17432. this.scheduler = scheduler;
  17433. }
  17434. TimeIntervalOperator.prototype.call = function (observer, source) {
  17435. return source.subscribe(new TimeIntervalSubscriber(observer, this.scheduler));
  17436. };
  17437. return TimeIntervalOperator;
  17438. }());
  17439. /**
  17440. * We need this JSDoc comment for affecting ESDoc.
  17441. * @ignore
  17442. * @extends {Ignored}
  17443. */
  17444. var TimeIntervalSubscriber = (function (_super) {
  17445. __extends(TimeIntervalSubscriber, _super);
  17446. function TimeIntervalSubscriber(destination, scheduler) {
  17447. _super.call(this, destination);
  17448. this.scheduler = scheduler;
  17449. this.lastTime = 0;
  17450. this.lastTime = scheduler.now();
  17451. }
  17452. TimeIntervalSubscriber.prototype._next = function (value) {
  17453. var now = this.scheduler.now();
  17454. var span = now - this.lastTime;
  17455. this.lastTime = now;
  17456. this.destination.next(new TimeInterval(value, span));
  17457. };
  17458. return TimeIntervalSubscriber;
  17459. }(Subscriber));
  17460. /**
  17461. * @param scheduler
  17462. * @return {Observable<TimeInterval<any>>|WebSocketSubject<T>|Observable<T>}
  17463. * @method timeInterval
  17464. * @owner Observable
  17465. */
  17466. function timeInterval$$1(scheduler) {
  17467. if (scheduler === void 0) { scheduler = async; }
  17468. return timeInterval$1(scheduler)(this);
  17469. }
  17470. Observable.prototype.timeInterval = timeInterval$$1;
  17471. /**
  17472. * An error thrown when duetime elapses.
  17473. *
  17474. * @see {@link timeout}
  17475. *
  17476. * @class TimeoutError
  17477. */
  17478. var TimeoutError = (function (_super) {
  17479. __extends(TimeoutError, _super);
  17480. function TimeoutError() {
  17481. var err = _super.call(this, 'Timeout has occurred');
  17482. this.name = err.name = 'TimeoutError';
  17483. this.stack = err.stack;
  17484. this.message = err.message;
  17485. }
  17486. return TimeoutError;
  17487. }(Error));
  17488. /**
  17489. *
  17490. * Errors if Observable does not emit a value in given time span.
  17491. *
  17492. * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
  17493. *
  17494. * <img src="./img/timeout.png" width="100%">
  17495. *
  17496. * `timeout` operator accepts as an argument either a number or a Date.
  17497. *
  17498. * If number was provided, it returns an Observable that behaves like a source
  17499. * Observable, unless there is a period of time where there is no value emitted.
  17500. * So if you provide `100` as argument and first value comes after 50ms from
  17501. * the moment of subscription, this value will be simply re-emitted by the resulting
  17502. * Observable. If however after that 100ms passes without a second value being emitted,
  17503. * stream will end with an error and source Observable will be unsubscribed.
  17504. * These checks are performed throughout whole lifecycle of Observable - from the moment
  17505. * it was subscribed to, until it completes or errors itself. Thus every value must be
  17506. * emitted within specified period since previous value.
  17507. *
  17508. * If provided argument was Date, returned Observable behaves differently. It throws
  17509. * if Observable did not complete before provided Date. This means that periods between
  17510. * emission of particular values do not matter in this case. If Observable did not complete
  17511. * before provided Date, source Observable will be unsubscribed. Other than that, resulting
  17512. * stream behaves just as source Observable.
  17513. *
  17514. * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
  17515. * when returned Observable will check if source stream emitted value or completed.
  17516. *
  17517. * @example <caption>Check if ticks are emitted within certain timespan</caption>
  17518. * const seconds = Rx.Observable.interval(1000);
  17519. *
  17520. * seconds.timeout(1100) // Let's use bigger timespan to be safe,
  17521. * // since `interval` might fire a bit later then scheduled.
  17522. * .subscribe(
  17523. * value => console.log(value), // Will emit numbers just as regular `interval` would.
  17524. * err => console.log(err) // Will never be called.
  17525. * );
  17526. *
  17527. * seconds.timeout(900).subscribe(
  17528. * value => console.log(value), // Will never be called.
  17529. * err => console.log(err) // Will emit error before even first value is emitted,
  17530. * // since it did not arrive within 900ms period.
  17531. * );
  17532. *
  17533. * @example <caption>Use Date to check if Observable completed</caption>
  17534. * const seconds = Rx.Observable.interval(1000);
  17535. *
  17536. * seconds.timeout(new Date("December 17, 2020 03:24:00"))
  17537. * .subscribe(
  17538. * value => console.log(value), // Will emit values as regular `interval` would
  17539. * // until December 17, 2020 at 03:24:00.
  17540. * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
  17541. * // since Observable did not complete by then.
  17542. * );
  17543. *
  17544. * @see {@link timeoutWith}
  17545. *
  17546. * @param {number|Date} due Number specifying period within which Observable must emit values
  17547. * or Date specifying before when Observable should complete
  17548. * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
  17549. * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
  17550. * @method timeout
  17551. * @owner Observable
  17552. */
  17553. function timeout$1(due, scheduler) {
  17554. if (scheduler === void 0) { scheduler = async; }
  17555. var absoluteTimeout = isDate(due);
  17556. var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
  17557. return function (source) { return source.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new TimeoutError())); };
  17558. }
  17559. var TimeoutOperator = (function () {
  17560. function TimeoutOperator(waitFor, absoluteTimeout, scheduler, errorInstance) {
  17561. this.waitFor = waitFor;
  17562. this.absoluteTimeout = absoluteTimeout;
  17563. this.scheduler = scheduler;
  17564. this.errorInstance = errorInstance;
  17565. }
  17566. TimeoutOperator.prototype.call = function (subscriber, source) {
  17567. return source.subscribe(new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.scheduler, this.errorInstance));
  17568. };
  17569. return TimeoutOperator;
  17570. }());
  17571. /**
  17572. * We need this JSDoc comment for affecting ESDoc.
  17573. * @ignore
  17574. * @extends {Ignored}
  17575. */
  17576. var TimeoutSubscriber = (function (_super) {
  17577. __extends(TimeoutSubscriber, _super);
  17578. function TimeoutSubscriber(destination, absoluteTimeout, waitFor, scheduler, errorInstance) {
  17579. _super.call(this, destination);
  17580. this.absoluteTimeout = absoluteTimeout;
  17581. this.waitFor = waitFor;
  17582. this.scheduler = scheduler;
  17583. this.errorInstance = errorInstance;
  17584. this.action = null;
  17585. this.scheduleTimeout();
  17586. }
  17587. TimeoutSubscriber.dispatchTimeout = function (subscriber) {
  17588. subscriber.error(subscriber.errorInstance);
  17589. };
  17590. TimeoutSubscriber.prototype.scheduleTimeout = function () {
  17591. var action = this.action;
  17592. if (action) {
  17593. // Recycle the action if we've already scheduled one. All the production
  17594. // Scheduler Actions mutate their state/delay time and return themeselves.
  17595. // VirtualActions are immutable, so they create and return a clone. In this
  17596. // case, we need to set the action reference to the most recent VirtualAction,
  17597. // to ensure that's the one we clone from next time.
  17598. this.action = action.schedule(this, this.waitFor);
  17599. }
  17600. else {
  17601. this.add(this.action = this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, this));
  17602. }
  17603. };
  17604. TimeoutSubscriber.prototype._next = function (value) {
  17605. if (!this.absoluteTimeout) {
  17606. this.scheduleTimeout();
  17607. }
  17608. _super.prototype._next.call(this, value);
  17609. };
  17610. /** @deprecated internal use only */ TimeoutSubscriber.prototype._unsubscribe = function () {
  17611. this.action = null;
  17612. this.scheduler = null;
  17613. this.errorInstance = null;
  17614. };
  17615. return TimeoutSubscriber;
  17616. }(Subscriber));
  17617. /**
  17618. *
  17619. * Errors if Observable does not emit a value in given time span.
  17620. *
  17621. * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
  17622. *
  17623. * <img src="./img/timeout.png" width="100%">
  17624. *
  17625. * `timeout` operator accepts as an argument either a number or a Date.
  17626. *
  17627. * If number was provided, it returns an Observable that behaves like a source
  17628. * Observable, unless there is a period of time where there is no value emitted.
  17629. * So if you provide `100` as argument and first value comes after 50ms from
  17630. * the moment of subscription, this value will be simply re-emitted by the resulting
  17631. * Observable. If however after that 100ms passes without a second value being emitted,
  17632. * stream will end with an error and source Observable will be unsubscribed.
  17633. * These checks are performed throughout whole lifecycle of Observable - from the moment
  17634. * it was subscribed to, until it completes or errors itself. Thus every value must be
  17635. * emitted within specified period since previous value.
  17636. *
  17637. * If provided argument was Date, returned Observable behaves differently. It throws
  17638. * if Observable did not complete before provided Date. This means that periods between
  17639. * emission of particular values do not matter in this case. If Observable did not complete
  17640. * before provided Date, source Observable will be unsubscribed. Other than that, resulting
  17641. * stream behaves just as source Observable.
  17642. *
  17643. * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
  17644. * when returned Observable will check if source stream emitted value or completed.
  17645. *
  17646. * @example <caption>Check if ticks are emitted within certain timespan</caption>
  17647. * const seconds = Rx.Observable.interval(1000);
  17648. *
  17649. * seconds.timeout(1100) // Let's use bigger timespan to be safe,
  17650. * // since `interval` might fire a bit later then scheduled.
  17651. * .subscribe(
  17652. * value => console.log(value), // Will emit numbers just as regular `interval` would.
  17653. * err => console.log(err) // Will never be called.
  17654. * );
  17655. *
  17656. * seconds.timeout(900).subscribe(
  17657. * value => console.log(value), // Will never be called.
  17658. * err => console.log(err) // Will emit error before even first value is emitted,
  17659. * // since it did not arrive within 900ms period.
  17660. * );
  17661. *
  17662. * @example <caption>Use Date to check if Observable completed</caption>
  17663. * const seconds = Rx.Observable.interval(1000);
  17664. *
  17665. * seconds.timeout(new Date("December 17, 2020 03:24:00"))
  17666. * .subscribe(
  17667. * value => console.log(value), // Will emit values as regular `interval` would
  17668. * // until December 17, 2020 at 03:24:00.
  17669. * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
  17670. * // since Observable did not complete by then.
  17671. * );
  17672. *
  17673. * @see {@link timeoutWith}
  17674. *
  17675. * @param {number|Date} due Number specifying period within which Observable must emit values
  17676. * or Date specifying before when Observable should complete
  17677. * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
  17678. * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
  17679. * @method timeout
  17680. * @owner Observable
  17681. */
  17682. function timeout$$1(due, scheduler) {
  17683. if (scheduler === void 0) { scheduler = async; }
  17684. return timeout$1(due, scheduler)(this);
  17685. }
  17686. Observable.prototype.timeout = timeout$$1;
  17687. /* tslint:enable:max-line-length */
  17688. /**
  17689. *
  17690. * Errors if Observable does not emit a value in given time span, in case of which
  17691. * subscribes to the second Observable.
  17692. *
  17693. * <span class="informal">It's a version of `timeout` operator that let's you specify fallback Observable.</span>
  17694. *
  17695. * <img src="./img/timeoutWith.png" width="100%">
  17696. *
  17697. * `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,
  17698. * still accepting as a first argument either a number or a Date, which control - respectively -
  17699. * when values of source Observable should be emitted or when it should complete.
  17700. *
  17701. * The only difference is that it accepts a second, required parameter. This parameter
  17702. * should be an Observable which will be subscribed when source Observable fails any timeout check.
  17703. * So whenever regular `timeout` would emit an error, `timeoutWith` will instead start re-emitting
  17704. * values from second Observable. Note that this fallback Observable is not checked for timeouts
  17705. * itself, so it can emit values and complete at arbitrary points in time. From the moment of a second
  17706. * subscription, Observable returned from `timeoutWith` simply mirrors fallback stream. When that
  17707. * stream completes, it completes as well.
  17708. *
  17709. * Scheduler, which in case of `timeout` is provided as as second argument, can be still provided
  17710. * here - as a third, optional parameter. It still is used to schedule timeout checks and -
  17711. * as a consequence - when second Observable will be subscribed, since subscription happens
  17712. * immediately after failing check.
  17713. *
  17714. * @example <caption>Add fallback observable</caption>
  17715. * const seconds = Rx.Observable.interval(1000);
  17716. * const minutes = Rx.Observable.interval(60 * 1000);
  17717. *
  17718. * seconds.timeoutWith(900, minutes)
  17719. * .subscribe(
  17720. * value => console.log(value), // After 900ms, will start emitting `minutes`,
  17721. * // since first value of `seconds` will not arrive fast enough.
  17722. * err => console.log(err) // Would be called after 900ms in case of `timeout`,
  17723. * // but here will never be called.
  17724. * );
  17725. *
  17726. * @param {number|Date} due Number specifying period within which Observable must emit values
  17727. * or Date specifying before when Observable should complete
  17728. * @param {Observable<T>} withObservable Observable which will be subscribed if source fails timeout check.
  17729. * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
  17730. * @return {Observable<T>} Observable that mirrors behaviour of source or, when timeout check fails, of an Observable
  17731. * passed as a second parameter.
  17732. * @method timeoutWith
  17733. * @owner Observable
  17734. */
  17735. function timeoutWith$1(due, withObservable, scheduler) {
  17736. if (scheduler === void 0) { scheduler = async; }
  17737. return function (source) {
  17738. var absoluteTimeout = isDate(due);
  17739. var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
  17740. return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
  17741. };
  17742. }
  17743. var TimeoutWithOperator = (function () {
  17744. function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {
  17745. this.waitFor = waitFor;
  17746. this.absoluteTimeout = absoluteTimeout;
  17747. this.withObservable = withObservable;
  17748. this.scheduler = scheduler;
  17749. }
  17750. TimeoutWithOperator.prototype.call = function (subscriber, source) {
  17751. return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
  17752. };
  17753. return TimeoutWithOperator;
  17754. }());
  17755. /**
  17756. * We need this JSDoc comment for affecting ESDoc.
  17757. * @ignore
  17758. * @extends {Ignored}
  17759. */
  17760. var TimeoutWithSubscriber = (function (_super) {
  17761. __extends(TimeoutWithSubscriber, _super);
  17762. function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
  17763. _super.call(this, destination);
  17764. this.absoluteTimeout = absoluteTimeout;
  17765. this.waitFor = waitFor;
  17766. this.withObservable = withObservable;
  17767. this.scheduler = scheduler;
  17768. this.action = null;
  17769. this.scheduleTimeout();
  17770. }
  17771. TimeoutWithSubscriber.dispatchTimeout = function (subscriber) {
  17772. var withObservable = subscriber.withObservable;
  17773. subscriber._unsubscribeAndRecycle();
  17774. subscriber.add(subscribeToResult(subscriber, withObservable));
  17775. };
  17776. TimeoutWithSubscriber.prototype.scheduleTimeout = function () {
  17777. var action = this.action;
  17778. if (action) {
  17779. // Recycle the action if we've already scheduled one. All the production
  17780. // Scheduler Actions mutate their state/delay time and return themeselves.
  17781. // VirtualActions are immutable, so they create and return a clone. In this
  17782. // case, we need to set the action reference to the most recent VirtualAction,
  17783. // to ensure that's the one we clone from next time.
  17784. this.action = action.schedule(this, this.waitFor);
  17785. }
  17786. else {
  17787. this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
  17788. }
  17789. };
  17790. TimeoutWithSubscriber.prototype._next = function (value) {
  17791. if (!this.absoluteTimeout) {
  17792. this.scheduleTimeout();
  17793. }
  17794. _super.prototype._next.call(this, value);
  17795. };
  17796. /** @deprecated internal use only */ TimeoutWithSubscriber.prototype._unsubscribe = function () {
  17797. this.action = null;
  17798. this.scheduler = null;
  17799. this.withObservable = null;
  17800. };
  17801. return TimeoutWithSubscriber;
  17802. }(OuterSubscriber));
  17803. /* tslint:enable:max-line-length */
  17804. /**
  17805. *
  17806. * Errors if Observable does not emit a value in given time span, in case of which
  17807. * subscribes to the second Observable.
  17808. *
  17809. * <span class="informal">It's a version of `timeout` operator that let's you specify fallback Observable.</span>
  17810. *
  17811. * <img src="./img/timeoutWith.png" width="100%">
  17812. *
  17813. * `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,
  17814. * still accepting as a first argument either a number or a Date, which control - respectively -
  17815. * when values of source Observable should be emitted or when it should complete.
  17816. *
  17817. * The only difference is that it accepts a second, required parameter. This parameter
  17818. * should be an Observable which will be subscribed when source Observable fails any timeout check.
  17819. * So whenever regular `timeout` would emit an error, `timeoutWith` will instead start re-emitting
  17820. * values from second Observable. Note that this fallback Observable is not checked for timeouts
  17821. * itself, so it can emit values and complete at arbitrary points in time. From the moment of a second
  17822. * subscription, Observable returned from `timeoutWith` simply mirrors fallback stream. When that
  17823. * stream completes, it completes as well.
  17824. *
  17825. * Scheduler, which in case of `timeout` is provided as as second argument, can be still provided
  17826. * here - as a third, optional parameter. It still is used to schedule timeout checks and -
  17827. * as a consequence - when second Observable will be subscribed, since subscription happens
  17828. * immediately after failing check.
  17829. *
  17830. * @example <caption>Add fallback observable</caption>
  17831. * const seconds = Rx.Observable.interval(1000);
  17832. * const minutes = Rx.Observable.interval(60 * 1000);
  17833. *
  17834. * seconds.timeoutWith(900, minutes)
  17835. * .subscribe(
  17836. * value => console.log(value), // After 900ms, will start emitting `minutes`,
  17837. * // since first value of `seconds` will not arrive fast enough.
  17838. * err => console.log(err) // Would be called after 900ms in case of `timeout`,
  17839. * // but here will never be called.
  17840. * );
  17841. *
  17842. * @param {number|Date} due Number specifying period within which Observable must emit values
  17843. * or Date specifying before when Observable should complete
  17844. * @param {Observable<T>} withObservable Observable which will be subscribed if source fails timeout check.
  17845. * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
  17846. * @return {Observable<T>} Observable that mirrors behaviour of source or, when timeout check fails, of an Observable
  17847. * passed as a second parameter.
  17848. * @method timeoutWith
  17849. * @owner Observable
  17850. */
  17851. function timeoutWith$$1(due, withObservable, scheduler) {
  17852. if (scheduler === void 0) { scheduler = async; }
  17853. return timeoutWith$1(due, withObservable, scheduler)(this);
  17854. }
  17855. Observable.prototype.timeoutWith = timeoutWith$$1;
  17856. /**
  17857. * @param scheduler
  17858. * @return {Observable<Timestamp<any>>|WebSocketSubject<T>|Observable<T>}
  17859. * @method timestamp
  17860. * @owner Observable
  17861. */
  17862. function timestamp$1(scheduler) {
  17863. if (scheduler === void 0) { scheduler = async; }
  17864. return map(function (value) { return new Timestamp(value, scheduler.now()); });
  17865. // return (source: Observable<T>) => source.lift(new TimestampOperator(scheduler));
  17866. }
  17867. var Timestamp = (function () {
  17868. function Timestamp(value, timestamp) {
  17869. this.value = value;
  17870. this.timestamp = timestamp;
  17871. }
  17872. return Timestamp;
  17873. }());
  17874. /**
  17875. * @param scheduler
  17876. * @return {Observable<Timestamp<any>>|WebSocketSubject<T>|Observable<T>}
  17877. * @method timestamp
  17878. * @owner Observable
  17879. */
  17880. function timestamp$$1(scheduler) {
  17881. if (scheduler === void 0) { scheduler = async; }
  17882. return timestamp$1(scheduler)(this);
  17883. }
  17884. Observable.prototype.timestamp = timestamp$$1;
  17885. function toArrayReducer(arr, item, index) {
  17886. if (index === 0) {
  17887. return [item];
  17888. }
  17889. arr.push(item);
  17890. return arr;
  17891. }
  17892. function toArray$1() {
  17893. return reduce(toArrayReducer, []);
  17894. }
  17895. /**
  17896. * Collects all source emissions and emits them as an array when the source completes.
  17897. *
  17898. * <span class="informal">Get all values inside an array when the source completes</span>
  17899. *
  17900. * <img src="./img/toArray.png" width="100%">
  17901. *
  17902. * `toArray` will wait until the source Observable completes
  17903. * before emitting the array containing all emissions.
  17904. * When the source Observable errors no array will be emitted.
  17905. *
  17906. * @example <caption>Create array from input</caption>
  17907. * const input = Rx.Observable.interval(100).take(4);
  17908. *
  17909. * input.toArray()
  17910. * .subscribe(arr => console.log(arr)); // [0,1,2,3]
  17911. *
  17912. * @see {@link buffer}
  17913. *
  17914. * @return {Observable<any[]>|WebSocketSubject<T>|Observable<T>}
  17915. * @method toArray
  17916. * @owner Observable
  17917. */
  17918. function toArray$$1() {
  17919. return toArray$1()(this);
  17920. }
  17921. Observable.prototype.toArray = toArray$$1;
  17922. // HACK: does nothing, because `toPromise` now lives on the `Observable` itself.
  17923. // leaving this module here to prevent breakage.
  17924. /**
  17925. * Branch out the source Observable values as a nested Observable whenever
  17926. * `windowBoundaries` emits.
  17927. *
  17928. * <span class="informal">It's like {@link buffer}, but emits a nested Observable
  17929. * instead of an array.</span>
  17930. *
  17931. * <img src="./img/window.png" width="100%">
  17932. *
  17933. * Returns an Observable that emits windows of items it collects from the source
  17934. * Observable. The output Observable emits connected, non-overlapping
  17935. * windows. It emits the current window and opens a new one whenever the
  17936. * Observable `windowBoundaries` emits an item. Because each window is an
  17937. * Observable, the output is a higher-order Observable.
  17938. *
  17939. * @example <caption>In every window of 1 second each, emit at most 2 click events</caption>
  17940. * var clicks = Rx.Observable.fromEvent(document, 'click');
  17941. * var interval = Rx.Observable.interval(1000);
  17942. * var result = clicks.window(interval)
  17943. * .map(win => win.take(2)) // each window has at most 2 emissions
  17944. * .mergeAll(); // flatten the Observable-of-Observables
  17945. * result.subscribe(x => console.log(x));
  17946. *
  17947. * @see {@link windowCount}
  17948. * @see {@link windowTime}
  17949. * @see {@link windowToggle}
  17950. * @see {@link windowWhen}
  17951. * @see {@link buffer}
  17952. *
  17953. * @param {Observable<any>} windowBoundaries An Observable that completes the
  17954. * previous window and starts a new window.
  17955. * @return {Observable<Observable<T>>} An Observable of windows, which are
  17956. * Observables emitting values of the source Observable.
  17957. * @method window
  17958. * @owner Observable
  17959. */
  17960. function window$2(windowBoundaries) {
  17961. return function windowOperatorFunction(source) {
  17962. return source.lift(new WindowOperator(windowBoundaries));
  17963. };
  17964. }
  17965. var WindowOperator = (function () {
  17966. function WindowOperator(windowBoundaries) {
  17967. this.windowBoundaries = windowBoundaries;
  17968. }
  17969. WindowOperator.prototype.call = function (subscriber, source) {
  17970. var windowSubscriber = new WindowSubscriber(subscriber);
  17971. var sourceSubscription = source.subscribe(windowSubscriber);
  17972. if (!sourceSubscription.closed) {
  17973. windowSubscriber.add(subscribeToResult(windowSubscriber, this.windowBoundaries));
  17974. }
  17975. return sourceSubscription;
  17976. };
  17977. return WindowOperator;
  17978. }());
  17979. /**
  17980. * We need this JSDoc comment for affecting ESDoc.
  17981. * @ignore
  17982. * @extends {Ignored}
  17983. */
  17984. var WindowSubscriber = (function (_super) {
  17985. __extends(WindowSubscriber, _super);
  17986. function WindowSubscriber(destination) {
  17987. _super.call(this, destination);
  17988. this.window = new Subject();
  17989. destination.next(this.window);
  17990. }
  17991. WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  17992. this.openWindow();
  17993. };
  17994. WindowSubscriber.prototype.notifyError = function (error, innerSub) {
  17995. this._error(error);
  17996. };
  17997. WindowSubscriber.prototype.notifyComplete = function (innerSub) {
  17998. this._complete();
  17999. };
  18000. WindowSubscriber.prototype._next = function (value) {
  18001. this.window.next(value);
  18002. };
  18003. WindowSubscriber.prototype._error = function (err) {
  18004. this.window.error(err);
  18005. this.destination.error(err);
  18006. };
  18007. WindowSubscriber.prototype._complete = function () {
  18008. this.window.complete();
  18009. this.destination.complete();
  18010. };
  18011. /** @deprecated internal use only */ WindowSubscriber.prototype._unsubscribe = function () {
  18012. this.window = null;
  18013. };
  18014. WindowSubscriber.prototype.openWindow = function () {
  18015. var prevWindow = this.window;
  18016. if (prevWindow) {
  18017. prevWindow.complete();
  18018. }
  18019. var destination = this.destination;
  18020. var newWindow = this.window = new Subject();
  18021. destination.next(newWindow);
  18022. };
  18023. return WindowSubscriber;
  18024. }(OuterSubscriber));
  18025. /**
  18026. * Branch out the source Observable values as a nested Observable whenever
  18027. * `windowBoundaries` emits.
  18028. *
  18029. * <span class="informal">It's like {@link buffer}, but emits a nested Observable
  18030. * instead of an array.</span>
  18031. *
  18032. * <img src="./img/window.png" width="100%">
  18033. *
  18034. * Returns an Observable that emits windows of items it collects from the source
  18035. * Observable. The output Observable emits connected, non-overlapping
  18036. * windows. It emits the current window and opens a new one whenever the
  18037. * Observable `windowBoundaries` emits an item. Because each window is an
  18038. * Observable, the output is a higher-order Observable.
  18039. *
  18040. * @example <caption>In every window of 1 second each, emit at most 2 click events</caption>
  18041. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18042. * var interval = Rx.Observable.interval(1000);
  18043. * var result = clicks.window(interval)
  18044. * .map(win => win.take(2)) // each window has at most 2 emissions
  18045. * .mergeAll(); // flatten the Observable-of-Observables
  18046. * result.subscribe(x => console.log(x));
  18047. *
  18048. * @see {@link windowCount}
  18049. * @see {@link windowTime}
  18050. * @see {@link windowToggle}
  18051. * @see {@link windowWhen}
  18052. * @see {@link buffer}
  18053. *
  18054. * @param {Observable<any>} windowBoundaries An Observable that completes the
  18055. * previous window and starts a new window.
  18056. * @return {Observable<Observable<T>>} An Observable of windows, which are
  18057. * Observables emitting values of the source Observable.
  18058. * @method window
  18059. * @owner Observable
  18060. */
  18061. function window$1(windowBoundaries) {
  18062. return window$2(windowBoundaries)(this);
  18063. }
  18064. Observable.prototype.window = window$1;
  18065. /**
  18066. * Branch out the source Observable values as a nested Observable with each
  18067. * nested Observable emitting at most `windowSize` values.
  18068. *
  18069. * <span class="informal">It's like {@link bufferCount}, but emits a nested
  18070. * Observable instead of an array.</span>
  18071. *
  18072. * <img src="./img/windowCount.png" width="100%">
  18073. *
  18074. * Returns an Observable that emits windows of items it collects from the source
  18075. * Observable. The output Observable emits windows every `startWindowEvery`
  18076. * items, each containing no more than `windowSize` items. When the source
  18077. * Observable completes or encounters an error, the output Observable emits
  18078. * the current window and propagates the notification from the source
  18079. * Observable. If `startWindowEvery` is not provided, then new windows are
  18080. * started immediately at the start of the source and when each window completes
  18081. * with size `windowSize`.
  18082. *
  18083. * @example <caption>Ignore every 3rd click event, starting from the first one</caption>
  18084. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18085. * var result = clicks.windowCount(3)
  18086. * .map(win => win.skip(1)) // skip first of every 3 clicks
  18087. * .mergeAll(); // flatten the Observable-of-Observables
  18088. * result.subscribe(x => console.log(x));
  18089. *
  18090. * @example <caption>Ignore every 3rd click event, starting from the third one</caption>
  18091. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18092. * var result = clicks.windowCount(2, 3)
  18093. * .mergeAll(); // flatten the Observable-of-Observables
  18094. * result.subscribe(x => console.log(x));
  18095. *
  18096. * @see {@link window}
  18097. * @see {@link windowTime}
  18098. * @see {@link windowToggle}
  18099. * @see {@link windowWhen}
  18100. * @see {@link bufferCount}
  18101. *
  18102. * @param {number} windowSize The maximum number of values emitted by each
  18103. * window.
  18104. * @param {number} [startWindowEvery] Interval at which to start a new window.
  18105. * For example if `startWindowEvery` is `2`, then a new window will be started
  18106. * on every other value from the source. A new window is started at the
  18107. * beginning of the source by default.
  18108. * @return {Observable<Observable<T>>} An Observable of windows, which in turn
  18109. * are Observable of values.
  18110. * @method windowCount
  18111. * @owner Observable
  18112. */
  18113. function windowCount$1(windowSize, startWindowEvery) {
  18114. if (startWindowEvery === void 0) { startWindowEvery = 0; }
  18115. return function windowCountOperatorFunction(source) {
  18116. return source.lift(new WindowCountOperator(windowSize, startWindowEvery));
  18117. };
  18118. }
  18119. var WindowCountOperator = (function () {
  18120. function WindowCountOperator(windowSize, startWindowEvery) {
  18121. this.windowSize = windowSize;
  18122. this.startWindowEvery = startWindowEvery;
  18123. }
  18124. WindowCountOperator.prototype.call = function (subscriber, source) {
  18125. return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));
  18126. };
  18127. return WindowCountOperator;
  18128. }());
  18129. /**
  18130. * We need this JSDoc comment for affecting ESDoc.
  18131. * @ignore
  18132. * @extends {Ignored}
  18133. */
  18134. var WindowCountSubscriber = (function (_super) {
  18135. __extends(WindowCountSubscriber, _super);
  18136. function WindowCountSubscriber(destination, windowSize, startWindowEvery) {
  18137. _super.call(this, destination);
  18138. this.destination = destination;
  18139. this.windowSize = windowSize;
  18140. this.startWindowEvery = startWindowEvery;
  18141. this.windows = [new Subject()];
  18142. this.count = 0;
  18143. destination.next(this.windows[0]);
  18144. }
  18145. WindowCountSubscriber.prototype._next = function (value) {
  18146. var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
  18147. var destination = this.destination;
  18148. var windowSize = this.windowSize;
  18149. var windows = this.windows;
  18150. var len = windows.length;
  18151. for (var i = 0; i < len && !this.closed; i++) {
  18152. windows[i].next(value);
  18153. }
  18154. var c = this.count - windowSize + 1;
  18155. if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {
  18156. windows.shift().complete();
  18157. }
  18158. if (++this.count % startWindowEvery === 0 && !this.closed) {
  18159. var window_1 = new Subject();
  18160. windows.push(window_1);
  18161. destination.next(window_1);
  18162. }
  18163. };
  18164. WindowCountSubscriber.prototype._error = function (err) {
  18165. var windows = this.windows;
  18166. if (windows) {
  18167. while (windows.length > 0 && !this.closed) {
  18168. windows.shift().error(err);
  18169. }
  18170. }
  18171. this.destination.error(err);
  18172. };
  18173. WindowCountSubscriber.prototype._complete = function () {
  18174. var windows = this.windows;
  18175. if (windows) {
  18176. while (windows.length > 0 && !this.closed) {
  18177. windows.shift().complete();
  18178. }
  18179. }
  18180. this.destination.complete();
  18181. };
  18182. /** @deprecated internal use only */ WindowCountSubscriber.prototype._unsubscribe = function () {
  18183. this.count = 0;
  18184. this.windows = null;
  18185. };
  18186. return WindowCountSubscriber;
  18187. }(Subscriber));
  18188. /**
  18189. * Branch out the source Observable values as a nested Observable with each
  18190. * nested Observable emitting at most `windowSize` values.
  18191. *
  18192. * <span class="informal">It's like {@link bufferCount}, but emits a nested
  18193. * Observable instead of an array.</span>
  18194. *
  18195. * <img src="./img/windowCount.png" width="100%">
  18196. *
  18197. * Returns an Observable that emits windows of items it collects from the source
  18198. * Observable. The output Observable emits windows every `startWindowEvery`
  18199. * items, each containing no more than `windowSize` items. When the source
  18200. * Observable completes or encounters an error, the output Observable emits
  18201. * the current window and propagates the notification from the source
  18202. * Observable. If `startWindowEvery` is not provided, then new windows are
  18203. * started immediately at the start of the source and when each window completes
  18204. * with size `windowSize`.
  18205. *
  18206. * @example <caption>Ignore every 3rd click event, starting from the first one</caption>
  18207. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18208. * var result = clicks.windowCount(3)
  18209. * .map(win => win.skip(1)) // skip first of every 3 clicks
  18210. * .mergeAll(); // flatten the Observable-of-Observables
  18211. * result.subscribe(x => console.log(x));
  18212. *
  18213. * @example <caption>Ignore every 3rd click event, starting from the third one</caption>
  18214. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18215. * var result = clicks.windowCount(2, 3)
  18216. * .mergeAll(); // flatten the Observable-of-Observables
  18217. * result.subscribe(x => console.log(x));
  18218. *
  18219. * @see {@link window}
  18220. * @see {@link windowTime}
  18221. * @see {@link windowToggle}
  18222. * @see {@link windowWhen}
  18223. * @see {@link bufferCount}
  18224. *
  18225. * @param {number} windowSize The maximum number of values emitted by each
  18226. * window.
  18227. * @param {number} [startWindowEvery] Interval at which to start a new window.
  18228. * For example if `startWindowEvery` is `2`, then a new window will be started
  18229. * on every other value from the source. A new window is started at the
  18230. * beginning of the source by default.
  18231. * @return {Observable<Observable<T>>} An Observable of windows, which in turn
  18232. * are Observable of values.
  18233. * @method windowCount
  18234. * @owner Observable
  18235. */
  18236. function windowCount$$1(windowSize, startWindowEvery) {
  18237. if (startWindowEvery === void 0) { startWindowEvery = 0; }
  18238. return windowCount$1(windowSize, startWindowEvery)(this);
  18239. }
  18240. Observable.prototype.windowCount = windowCount$$1;
  18241. function windowTime$1(windowTimeSpan) {
  18242. var scheduler = async;
  18243. var windowCreationInterval = null;
  18244. var maxWindowSize = Number.POSITIVE_INFINITY;
  18245. if (isScheduler(arguments[3])) {
  18246. scheduler = arguments[3];
  18247. }
  18248. if (isScheduler(arguments[2])) {
  18249. scheduler = arguments[2];
  18250. }
  18251. else if (isNumeric(arguments[2])) {
  18252. maxWindowSize = arguments[2];
  18253. }
  18254. if (isScheduler(arguments[1])) {
  18255. scheduler = arguments[1];
  18256. }
  18257. else if (isNumeric(arguments[1])) {
  18258. windowCreationInterval = arguments[1];
  18259. }
  18260. return function windowTimeOperatorFunction(source) {
  18261. return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));
  18262. };
  18263. }
  18264. var WindowTimeOperator = (function () {
  18265. function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
  18266. this.windowTimeSpan = windowTimeSpan;
  18267. this.windowCreationInterval = windowCreationInterval;
  18268. this.maxWindowSize = maxWindowSize;
  18269. this.scheduler = scheduler;
  18270. }
  18271. WindowTimeOperator.prototype.call = function (subscriber, source) {
  18272. return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler));
  18273. };
  18274. return WindowTimeOperator;
  18275. }());
  18276. var CountedSubject = (function (_super) {
  18277. __extends(CountedSubject, _super);
  18278. function CountedSubject() {
  18279. _super.apply(this, arguments);
  18280. this._numberOfNextedValues = 0;
  18281. }
  18282. CountedSubject.prototype.next = function (value) {
  18283. this._numberOfNextedValues++;
  18284. _super.prototype.next.call(this, value);
  18285. };
  18286. Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", {
  18287. get: function () {
  18288. return this._numberOfNextedValues;
  18289. },
  18290. enumerable: true,
  18291. configurable: true
  18292. });
  18293. return CountedSubject;
  18294. }(Subject));
  18295. /**
  18296. * We need this JSDoc comment for affecting ESDoc.
  18297. * @ignore
  18298. * @extends {Ignored}
  18299. */
  18300. var WindowTimeSubscriber = (function (_super) {
  18301. __extends(WindowTimeSubscriber, _super);
  18302. function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
  18303. _super.call(this, destination);
  18304. this.destination = destination;
  18305. this.windowTimeSpan = windowTimeSpan;
  18306. this.windowCreationInterval = windowCreationInterval;
  18307. this.maxWindowSize = maxWindowSize;
  18308. this.scheduler = scheduler;
  18309. this.windows = [];
  18310. var window = this.openWindow();
  18311. if (windowCreationInterval !== null && windowCreationInterval >= 0) {
  18312. var closeState = { subscriber: this, window: window, context: null };
  18313. var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: this, scheduler: scheduler };
  18314. this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState));
  18315. this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState));
  18316. }
  18317. else {
  18318. var timeSpanOnlyState = { subscriber: this, window: window, windowTimeSpan: windowTimeSpan };
  18319. this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));
  18320. }
  18321. }
  18322. WindowTimeSubscriber.prototype._next = function (value) {
  18323. var windows = this.windows;
  18324. var len = windows.length;
  18325. for (var i = 0; i < len; i++) {
  18326. var window_1 = windows[i];
  18327. if (!window_1.closed) {
  18328. window_1.next(value);
  18329. if (window_1.numberOfNextedValues >= this.maxWindowSize) {
  18330. this.closeWindow(window_1);
  18331. }
  18332. }
  18333. }
  18334. };
  18335. WindowTimeSubscriber.prototype._error = function (err) {
  18336. var windows = this.windows;
  18337. while (windows.length > 0) {
  18338. windows.shift().error(err);
  18339. }
  18340. this.destination.error(err);
  18341. };
  18342. WindowTimeSubscriber.prototype._complete = function () {
  18343. var windows = this.windows;
  18344. while (windows.length > 0) {
  18345. var window_2 = windows.shift();
  18346. if (!window_2.closed) {
  18347. window_2.complete();
  18348. }
  18349. }
  18350. this.destination.complete();
  18351. };
  18352. WindowTimeSubscriber.prototype.openWindow = function () {
  18353. var window = new CountedSubject();
  18354. this.windows.push(window);
  18355. var destination = this.destination;
  18356. destination.next(window);
  18357. return window;
  18358. };
  18359. WindowTimeSubscriber.prototype.closeWindow = function (window) {
  18360. window.complete();
  18361. var windows = this.windows;
  18362. windows.splice(windows.indexOf(window), 1);
  18363. };
  18364. return WindowTimeSubscriber;
  18365. }(Subscriber));
  18366. function dispatchWindowTimeSpanOnly(state) {
  18367. var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window;
  18368. if (window) {
  18369. subscriber.closeWindow(window);
  18370. }
  18371. state.window = subscriber.openWindow();
  18372. this.schedule(state, windowTimeSpan);
  18373. }
  18374. function dispatchWindowCreation(state) {
  18375. var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval;
  18376. var window = subscriber.openWindow();
  18377. var action = this;
  18378. var context = { action: action, subscription: null };
  18379. var timeSpanState = { subscriber: subscriber, window: window, context: context };
  18380. context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState);
  18381. action.add(context.subscription);
  18382. action.schedule(state, windowCreationInterval);
  18383. }
  18384. function dispatchWindowClose(state) {
  18385. var subscriber = state.subscriber, window = state.window, context = state.context;
  18386. if (context && context.action && context.subscription) {
  18387. context.action.remove(context.subscription);
  18388. }
  18389. subscriber.closeWindow(window);
  18390. }
  18391. function windowTime$$1(windowTimeSpan) {
  18392. var scheduler = async;
  18393. var windowCreationInterval = null;
  18394. var maxWindowSize = Number.POSITIVE_INFINITY;
  18395. if (isScheduler(arguments[3])) {
  18396. scheduler = arguments[3];
  18397. }
  18398. if (isScheduler(arguments[2])) {
  18399. scheduler = arguments[2];
  18400. }
  18401. else if (isNumeric(arguments[2])) {
  18402. maxWindowSize = arguments[2];
  18403. }
  18404. if (isScheduler(arguments[1])) {
  18405. scheduler = arguments[1];
  18406. }
  18407. else if (isNumeric(arguments[1])) {
  18408. windowCreationInterval = arguments[1];
  18409. }
  18410. return windowTime$1(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler)(this);
  18411. }
  18412. Observable.prototype.windowTime = windowTime$$1;
  18413. /**
  18414. * Branch out the source Observable values as a nested Observable starting from
  18415. * an emission from `openings` and ending when the output of `closingSelector`
  18416. * emits.
  18417. *
  18418. * <span class="informal">It's like {@link bufferToggle}, but emits a nested
  18419. * Observable instead of an array.</span>
  18420. *
  18421. * <img src="./img/windowToggle.png" width="100%">
  18422. *
  18423. * Returns an Observable that emits windows of items it collects from the source
  18424. * Observable. The output Observable emits windows that contain those items
  18425. * emitted by the source Observable between the time when the `openings`
  18426. * Observable emits an item and when the Observable returned by
  18427. * `closingSelector` emits an item.
  18428. *
  18429. * @example <caption>Every other second, emit the click events from the next 500ms</caption>
  18430. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18431. * var openings = Rx.Observable.interval(1000);
  18432. * var result = clicks.windowToggle(openings, i =>
  18433. * i % 2 ? Rx.Observable.interval(500) : Rx.Observable.empty()
  18434. * ).mergeAll();
  18435. * result.subscribe(x => console.log(x));
  18436. *
  18437. * @see {@link window}
  18438. * @see {@link windowCount}
  18439. * @see {@link windowTime}
  18440. * @see {@link windowWhen}
  18441. * @see {@link bufferToggle}
  18442. *
  18443. * @param {Observable<O>} openings An observable of notifications to start new
  18444. * windows.
  18445. * @param {function(value: O): Observable} closingSelector A function that takes
  18446. * the value emitted by the `openings` observable and returns an Observable,
  18447. * which, when it emits (either `next` or `complete`), signals that the
  18448. * associated window should complete.
  18449. * @return {Observable<Observable<T>>} An observable of windows, which in turn
  18450. * are Observables.
  18451. * @method windowToggle
  18452. * @owner Observable
  18453. */
  18454. function windowToggle$1(openings, closingSelector) {
  18455. return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); };
  18456. }
  18457. var WindowToggleOperator = (function () {
  18458. function WindowToggleOperator(openings, closingSelector) {
  18459. this.openings = openings;
  18460. this.closingSelector = closingSelector;
  18461. }
  18462. WindowToggleOperator.prototype.call = function (subscriber, source) {
  18463. return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector));
  18464. };
  18465. return WindowToggleOperator;
  18466. }());
  18467. /**
  18468. * We need this JSDoc comment for affecting ESDoc.
  18469. * @ignore
  18470. * @extends {Ignored}
  18471. */
  18472. var WindowToggleSubscriber = (function (_super) {
  18473. __extends(WindowToggleSubscriber, _super);
  18474. function WindowToggleSubscriber(destination, openings, closingSelector) {
  18475. _super.call(this, destination);
  18476. this.openings = openings;
  18477. this.closingSelector = closingSelector;
  18478. this.contexts = [];
  18479. this.add(this.openSubscription = subscribeToResult(this, openings, openings));
  18480. }
  18481. WindowToggleSubscriber.prototype._next = function (value) {
  18482. var contexts = this.contexts;
  18483. if (contexts) {
  18484. var len = contexts.length;
  18485. for (var i = 0; i < len; i++) {
  18486. contexts[i].window.next(value);
  18487. }
  18488. }
  18489. };
  18490. WindowToggleSubscriber.prototype._error = function (err) {
  18491. var contexts = this.contexts;
  18492. this.contexts = null;
  18493. if (contexts) {
  18494. var len = contexts.length;
  18495. var index = -1;
  18496. while (++index < len) {
  18497. var context = contexts[index];
  18498. context.window.error(err);
  18499. context.subscription.unsubscribe();
  18500. }
  18501. }
  18502. _super.prototype._error.call(this, err);
  18503. };
  18504. WindowToggleSubscriber.prototype._complete = function () {
  18505. var contexts = this.contexts;
  18506. this.contexts = null;
  18507. if (contexts) {
  18508. var len = contexts.length;
  18509. var index = -1;
  18510. while (++index < len) {
  18511. var context = contexts[index];
  18512. context.window.complete();
  18513. context.subscription.unsubscribe();
  18514. }
  18515. }
  18516. _super.prototype._complete.call(this);
  18517. };
  18518. /** @deprecated internal use only */ WindowToggleSubscriber.prototype._unsubscribe = function () {
  18519. var contexts = this.contexts;
  18520. this.contexts = null;
  18521. if (contexts) {
  18522. var len = contexts.length;
  18523. var index = -1;
  18524. while (++index < len) {
  18525. var context = contexts[index];
  18526. context.window.unsubscribe();
  18527. context.subscription.unsubscribe();
  18528. }
  18529. }
  18530. };
  18531. WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  18532. if (outerValue === this.openings) {
  18533. var closingSelector = this.closingSelector;
  18534. var closingNotifier = tryCatch(closingSelector)(innerValue);
  18535. if (closingNotifier === errorObject) {
  18536. return this.error(errorObject.e);
  18537. }
  18538. else {
  18539. var window_1 = new Subject();
  18540. var subscription = new Subscription();
  18541. var context = { window: window_1, subscription: subscription };
  18542. this.contexts.push(context);
  18543. var innerSubscription = subscribeToResult(this, closingNotifier, context);
  18544. if (innerSubscription.closed) {
  18545. this.closeWindow(this.contexts.length - 1);
  18546. }
  18547. else {
  18548. innerSubscription.context = context;
  18549. subscription.add(innerSubscription);
  18550. }
  18551. this.destination.next(window_1);
  18552. }
  18553. }
  18554. else {
  18555. this.closeWindow(this.contexts.indexOf(outerValue));
  18556. }
  18557. };
  18558. WindowToggleSubscriber.prototype.notifyError = function (err) {
  18559. this.error(err);
  18560. };
  18561. WindowToggleSubscriber.prototype.notifyComplete = function (inner) {
  18562. if (inner !== this.openSubscription) {
  18563. this.closeWindow(this.contexts.indexOf(inner.context));
  18564. }
  18565. };
  18566. WindowToggleSubscriber.prototype.closeWindow = function (index) {
  18567. if (index === -1) {
  18568. return;
  18569. }
  18570. var contexts = this.contexts;
  18571. var context = contexts[index];
  18572. var window = context.window, subscription = context.subscription;
  18573. contexts.splice(index, 1);
  18574. window.complete();
  18575. subscription.unsubscribe();
  18576. };
  18577. return WindowToggleSubscriber;
  18578. }(OuterSubscriber));
  18579. /**
  18580. * Branch out the source Observable values as a nested Observable starting from
  18581. * an emission from `openings` and ending when the output of `closingSelector`
  18582. * emits.
  18583. *
  18584. * <span class="informal">It's like {@link bufferToggle}, but emits a nested
  18585. * Observable instead of an array.</span>
  18586. *
  18587. * <img src="./img/windowToggle.png" width="100%">
  18588. *
  18589. * Returns an Observable that emits windows of items it collects from the source
  18590. * Observable. The output Observable emits windows that contain those items
  18591. * emitted by the source Observable between the time when the `openings`
  18592. * Observable emits an item and when the Observable returned by
  18593. * `closingSelector` emits an item.
  18594. *
  18595. * @example <caption>Every other second, emit the click events from the next 500ms</caption>
  18596. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18597. * var openings = Rx.Observable.interval(1000);
  18598. * var result = clicks.windowToggle(openings, i =>
  18599. * i % 2 ? Rx.Observable.interval(500) : Rx.Observable.empty()
  18600. * ).mergeAll();
  18601. * result.subscribe(x => console.log(x));
  18602. *
  18603. * @see {@link window}
  18604. * @see {@link windowCount}
  18605. * @see {@link windowTime}
  18606. * @see {@link windowWhen}
  18607. * @see {@link bufferToggle}
  18608. *
  18609. * @param {Observable<O>} openings An observable of notifications to start new
  18610. * windows.
  18611. * @param {function(value: O): Observable} closingSelector A function that takes
  18612. * the value emitted by the `openings` observable and returns an Observable,
  18613. * which, when it emits (either `next` or `complete`), signals that the
  18614. * associated window should complete.
  18615. * @return {Observable<Observable<T>>} An observable of windows, which in turn
  18616. * are Observables.
  18617. * @method windowToggle
  18618. * @owner Observable
  18619. */
  18620. function windowToggle$$1(openings, closingSelector) {
  18621. return windowToggle$1(openings, closingSelector)(this);
  18622. }
  18623. Observable.prototype.windowToggle = windowToggle$$1;
  18624. /**
  18625. * Branch out the source Observable values as a nested Observable using a
  18626. * factory function of closing Observables to determine when to start a new
  18627. * window.
  18628. *
  18629. * <span class="informal">It's like {@link bufferWhen}, but emits a nested
  18630. * Observable instead of an array.</span>
  18631. *
  18632. * <img src="./img/windowWhen.png" width="100%">
  18633. *
  18634. * Returns an Observable that emits windows of items it collects from the source
  18635. * Observable. The output Observable emits connected, non-overlapping windows.
  18636. * It emits the current window and opens a new one whenever the Observable
  18637. * produced by the specified `closingSelector` function emits an item. The first
  18638. * window is opened immediately when subscribing to the output Observable.
  18639. *
  18640. * @example <caption>Emit only the first two clicks events in every window of [1-5] random seconds</caption>
  18641. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18642. * var result = clicks
  18643. * .windowWhen(() => Rx.Observable.interval(1000 + Math.random() * 4000))
  18644. * .map(win => win.take(2)) // each window has at most 2 emissions
  18645. * .mergeAll(); // flatten the Observable-of-Observables
  18646. * result.subscribe(x => console.log(x));
  18647. *
  18648. * @see {@link window}
  18649. * @see {@link windowCount}
  18650. * @see {@link windowTime}
  18651. * @see {@link windowToggle}
  18652. * @see {@link bufferWhen}
  18653. *
  18654. * @param {function(): Observable} closingSelector A function that takes no
  18655. * arguments and returns an Observable that signals (on either `next` or
  18656. * `complete`) when to close the previous window and start a new one.
  18657. * @return {Observable<Observable<T>>} An observable of windows, which in turn
  18658. * are Observables.
  18659. * @method windowWhen
  18660. * @owner Observable
  18661. */
  18662. function windowWhen$1(closingSelector) {
  18663. return function windowWhenOperatorFunction(source) {
  18664. return source.lift(new WindowOperator$1(closingSelector));
  18665. };
  18666. }
  18667. var WindowOperator$1 = (function () {
  18668. function WindowOperator(closingSelector) {
  18669. this.closingSelector = closingSelector;
  18670. }
  18671. WindowOperator.prototype.call = function (subscriber, source) {
  18672. return source.subscribe(new WindowSubscriber$1(subscriber, this.closingSelector));
  18673. };
  18674. return WindowOperator;
  18675. }());
  18676. /**
  18677. * We need this JSDoc comment for affecting ESDoc.
  18678. * @ignore
  18679. * @extends {Ignored}
  18680. */
  18681. var WindowSubscriber$1 = (function (_super) {
  18682. __extends(WindowSubscriber, _super);
  18683. function WindowSubscriber(destination, closingSelector) {
  18684. _super.call(this, destination);
  18685. this.destination = destination;
  18686. this.closingSelector = closingSelector;
  18687. this.openWindow();
  18688. }
  18689. WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  18690. this.openWindow(innerSub);
  18691. };
  18692. WindowSubscriber.prototype.notifyError = function (error, innerSub) {
  18693. this._error(error);
  18694. };
  18695. WindowSubscriber.prototype.notifyComplete = function (innerSub) {
  18696. this.openWindow(innerSub);
  18697. };
  18698. WindowSubscriber.prototype._next = function (value) {
  18699. this.window.next(value);
  18700. };
  18701. WindowSubscriber.prototype._error = function (err) {
  18702. this.window.error(err);
  18703. this.destination.error(err);
  18704. this.unsubscribeClosingNotification();
  18705. };
  18706. WindowSubscriber.prototype._complete = function () {
  18707. this.window.complete();
  18708. this.destination.complete();
  18709. this.unsubscribeClosingNotification();
  18710. };
  18711. WindowSubscriber.prototype.unsubscribeClosingNotification = function () {
  18712. if (this.closingNotification) {
  18713. this.closingNotification.unsubscribe();
  18714. }
  18715. };
  18716. WindowSubscriber.prototype.openWindow = function (innerSub) {
  18717. if (innerSub === void 0) { innerSub = null; }
  18718. if (innerSub) {
  18719. this.remove(innerSub);
  18720. innerSub.unsubscribe();
  18721. }
  18722. var prevWindow = this.window;
  18723. if (prevWindow) {
  18724. prevWindow.complete();
  18725. }
  18726. var window = this.window = new Subject();
  18727. this.destination.next(window);
  18728. var closingNotifier = tryCatch(this.closingSelector)();
  18729. if (closingNotifier === errorObject) {
  18730. var err = errorObject.e;
  18731. this.destination.error(err);
  18732. this.window.error(err);
  18733. }
  18734. else {
  18735. this.add(this.closingNotification = subscribeToResult(this, closingNotifier));
  18736. }
  18737. };
  18738. return WindowSubscriber;
  18739. }(OuterSubscriber));
  18740. /**
  18741. * Branch out the source Observable values as a nested Observable using a
  18742. * factory function of closing Observables to determine when to start a new
  18743. * window.
  18744. *
  18745. * <span class="informal">It's like {@link bufferWhen}, but emits a nested
  18746. * Observable instead of an array.</span>
  18747. *
  18748. * <img src="./img/windowWhen.png" width="100%">
  18749. *
  18750. * Returns an Observable that emits windows of items it collects from the source
  18751. * Observable. The output Observable emits connected, non-overlapping windows.
  18752. * It emits the current window and opens a new one whenever the Observable
  18753. * produced by the specified `closingSelector` function emits an item. The first
  18754. * window is opened immediately when subscribing to the output Observable.
  18755. *
  18756. * @example <caption>Emit only the first two clicks events in every window of [1-5] random seconds</caption>
  18757. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18758. * var result = clicks
  18759. * .windowWhen(() => Rx.Observable.interval(1000 + Math.random() * 4000))
  18760. * .map(win => win.take(2)) // each window has at most 2 emissions
  18761. * .mergeAll(); // flatten the Observable-of-Observables
  18762. * result.subscribe(x => console.log(x));
  18763. *
  18764. * @see {@link window}
  18765. * @see {@link windowCount}
  18766. * @see {@link windowTime}
  18767. * @see {@link windowToggle}
  18768. * @see {@link bufferWhen}
  18769. *
  18770. * @param {function(): Observable} closingSelector A function that takes no
  18771. * arguments and returns an Observable that signals (on either `next` or
  18772. * `complete`) when to close the previous window and start a new one.
  18773. * @return {Observable<Observable<T>>} An observable of windows, which in turn
  18774. * are Observables.
  18775. * @method windowWhen
  18776. * @owner Observable
  18777. */
  18778. function windowWhen$$1(closingSelector) {
  18779. return windowWhen$1(closingSelector)(this);
  18780. }
  18781. Observable.prototype.windowWhen = windowWhen$$1;
  18782. /* tslint:enable:max-line-length */
  18783. /**
  18784. * Combines the source Observable with other Observables to create an Observable
  18785. * whose values are calculated from the latest values of each, only when the
  18786. * source emits.
  18787. *
  18788. * <span class="informal">Whenever the source Observable emits a value, it
  18789. * computes a formula using that value plus the latest values from other input
  18790. * Observables, then emits the output of that formula.</span>
  18791. *
  18792. * <img src="./img/withLatestFrom.png" width="100%">
  18793. *
  18794. * `withLatestFrom` combines each value from the source Observable (the
  18795. * instance) with the latest values from the other input Observables only when
  18796. * the source emits a value, optionally using a `project` function to determine
  18797. * the value to be emitted on the output Observable. All input Observables must
  18798. * emit at least one value before the output Observable will emit a value.
  18799. *
  18800. * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
  18801. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18802. * var timer = Rx.Observable.interval(1000);
  18803. * var result = clicks.withLatestFrom(timer);
  18804. * result.subscribe(x => console.log(x));
  18805. *
  18806. * @see {@link combineLatest}
  18807. *
  18808. * @param {ObservableInput} other An input Observable to combine with the source
  18809. * Observable. More than one input Observables may be given as argument.
  18810. * @param {Function} [project] Projection function for combining values
  18811. * together. Receives all values in order of the Observables passed, where the
  18812. * first parameter is a value from the source Observable. (e.g.
  18813. * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
  18814. * passed, arrays will be emitted on the output Observable.
  18815. * @return {Observable} An Observable of projected values from the most recent
  18816. * values from each input Observable, or an array of the most recent values from
  18817. * each input Observable.
  18818. * @method withLatestFrom
  18819. * @owner Observable
  18820. */
  18821. function withLatestFrom$1() {
  18822. var args = [];
  18823. for (var _i = 0; _i < arguments.length; _i++) {
  18824. args[_i - 0] = arguments[_i];
  18825. }
  18826. return function (source) {
  18827. var project;
  18828. if (typeof args[args.length - 1] === 'function') {
  18829. project = args.pop();
  18830. }
  18831. var observables = args;
  18832. return source.lift(new WithLatestFromOperator(observables, project));
  18833. };
  18834. }
  18835. var WithLatestFromOperator = (function () {
  18836. function WithLatestFromOperator(observables, project) {
  18837. this.observables = observables;
  18838. this.project = project;
  18839. }
  18840. WithLatestFromOperator.prototype.call = function (subscriber, source) {
  18841. return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
  18842. };
  18843. return WithLatestFromOperator;
  18844. }());
  18845. /**
  18846. * We need this JSDoc comment for affecting ESDoc.
  18847. * @ignore
  18848. * @extends {Ignored}
  18849. */
  18850. var WithLatestFromSubscriber = (function (_super) {
  18851. __extends(WithLatestFromSubscriber, _super);
  18852. function WithLatestFromSubscriber(destination, observables, project) {
  18853. _super.call(this, destination);
  18854. this.observables = observables;
  18855. this.project = project;
  18856. this.toRespond = [];
  18857. var len = observables.length;
  18858. this.values = new Array(len);
  18859. for (var i = 0; i < len; i++) {
  18860. this.toRespond.push(i);
  18861. }
  18862. for (var i = 0; i < len; i++) {
  18863. var observable = observables[i];
  18864. this.add(subscribeToResult(this, observable, observable, i));
  18865. }
  18866. }
  18867. WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  18868. this.values[outerIndex] = innerValue;
  18869. var toRespond = this.toRespond;
  18870. if (toRespond.length > 0) {
  18871. var found = toRespond.indexOf(outerIndex);
  18872. if (found !== -1) {
  18873. toRespond.splice(found, 1);
  18874. }
  18875. }
  18876. };
  18877. WithLatestFromSubscriber.prototype.notifyComplete = function () {
  18878. // noop
  18879. };
  18880. WithLatestFromSubscriber.prototype._next = function (value) {
  18881. if (this.toRespond.length === 0) {
  18882. var args = [value].concat(this.values);
  18883. if (this.project) {
  18884. this._tryProject(args);
  18885. }
  18886. else {
  18887. this.destination.next(args);
  18888. }
  18889. }
  18890. };
  18891. WithLatestFromSubscriber.prototype._tryProject = function (args) {
  18892. var result;
  18893. try {
  18894. result = this.project.apply(this, args);
  18895. }
  18896. catch (err) {
  18897. this.destination.error(err);
  18898. return;
  18899. }
  18900. this.destination.next(result);
  18901. };
  18902. return WithLatestFromSubscriber;
  18903. }(OuterSubscriber));
  18904. /* tslint:enable:max-line-length */
  18905. /**
  18906. * Combines the source Observable with other Observables to create an Observable
  18907. * whose values are calculated from the latest values of each, only when the
  18908. * source emits.
  18909. *
  18910. * <span class="informal">Whenever the source Observable emits a value, it
  18911. * computes a formula using that value plus the latest values from other input
  18912. * Observables, then emits the output of that formula.</span>
  18913. *
  18914. * <img src="./img/withLatestFrom.png" width="100%">
  18915. *
  18916. * `withLatestFrom` combines each value from the source Observable (the
  18917. * instance) with the latest values from the other input Observables only when
  18918. * the source emits a value, optionally using a `project` function to determine
  18919. * the value to be emitted on the output Observable. All input Observables must
  18920. * emit at least one value before the output Observable will emit a value.
  18921. *
  18922. * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
  18923. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18924. * var timer = Rx.Observable.interval(1000);
  18925. * var result = clicks.withLatestFrom(timer);
  18926. * result.subscribe(x => console.log(x));
  18927. *
  18928. * @see {@link combineLatest}
  18929. *
  18930. * @param {ObservableInput} other An input Observable to combine with the source
  18931. * Observable. More than one input Observables may be given as argument.
  18932. * @param {Function} [project] Projection function for combining values
  18933. * together. Receives all values in order of the Observables passed, where the
  18934. * first parameter is a value from the source Observable. (e.g.
  18935. * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
  18936. * passed, arrays will be emitted on the output Observable.
  18937. * @return {Observable} An Observable of projected values from the most recent
  18938. * values from each input Observable, or an array of the most recent values from
  18939. * each input Observable.
  18940. * @method withLatestFrom
  18941. * @owner Observable
  18942. */
  18943. function withLatestFrom$$1() {
  18944. var args = [];
  18945. for (var _i = 0; _i < arguments.length; _i++) {
  18946. args[_i - 0] = arguments[_i];
  18947. }
  18948. return withLatestFrom$1.apply(void 0, args)(this);
  18949. }
  18950. Observable.prototype.withLatestFrom = withLatestFrom$$1;
  18951. /* tslint:enable:max-line-length */
  18952. /**
  18953. * @param observables
  18954. * @return {Observable<R>}
  18955. * @method zip
  18956. * @owner Observable
  18957. */
  18958. function zipProto() {
  18959. var observables = [];
  18960. for (var _i = 0; _i < arguments.length; _i++) {
  18961. observables[_i - 0] = arguments[_i];
  18962. }
  18963. return zip$1.apply(void 0, observables)(this);
  18964. }
  18965. Observable.prototype.zip = zipProto;
  18966. function zipAll$1(project) {
  18967. return function (source) { return source.lift(new ZipOperator(project)); };
  18968. }
  18969. /**
  18970. * @param project
  18971. * @return {Observable<R>|WebSocketSubject<T>|Observable<T>}
  18972. * @method zipAll
  18973. * @owner Observable
  18974. */
  18975. function zipAll$$1(project) {
  18976. return zipAll$1(project)(this);
  18977. }
  18978. Observable.prototype.zipAll = zipAll$$1;
  18979. var SubscriptionLog = (function () {
  18980. function SubscriptionLog(subscribedFrame, unsubscribedFrame) {
  18981. if (unsubscribedFrame === void 0) { unsubscribedFrame = Number.POSITIVE_INFINITY; }
  18982. this.subscribedFrame = subscribedFrame;
  18983. this.unsubscribedFrame = unsubscribedFrame;
  18984. }
  18985. return SubscriptionLog;
  18986. }());
  18987. var SubscriptionLoggable = (function () {
  18988. function SubscriptionLoggable() {
  18989. this.subscriptions = [];
  18990. }
  18991. SubscriptionLoggable.prototype.logSubscribedFrame = function () {
  18992. this.subscriptions.push(new SubscriptionLog(this.scheduler.now()));
  18993. return this.subscriptions.length - 1;
  18994. };
  18995. SubscriptionLoggable.prototype.logUnsubscribedFrame = function (index) {
  18996. var subscriptionLogs = this.subscriptions;
  18997. var oldSubscriptionLog = subscriptionLogs[index];
  18998. subscriptionLogs[index] = new SubscriptionLog(oldSubscriptionLog.subscribedFrame, this.scheduler.now());
  18999. };
  19000. return SubscriptionLoggable;
  19001. }());
  19002. function applyMixins(derivedCtor, baseCtors) {
  19003. for (var i = 0, len = baseCtors.length; i < len; i++) {
  19004. var baseCtor = baseCtors[i];
  19005. var propertyKeys = Object.getOwnPropertyNames(baseCtor.prototype);
  19006. for (var j = 0, len2 = propertyKeys.length; j < len2; j++) {
  19007. var name_1 = propertyKeys[j];
  19008. derivedCtor.prototype[name_1] = baseCtor.prototype[name_1];
  19009. }
  19010. }
  19011. }
  19012. /**
  19013. * We need this JSDoc comment for affecting ESDoc.
  19014. * @ignore
  19015. * @extends {Ignored}
  19016. */
  19017. var ColdObservable = (function (_super) {
  19018. __extends(ColdObservable, _super);
  19019. function ColdObservable(messages, scheduler) {
  19020. _super.call(this, function (subscriber) {
  19021. var observable = this;
  19022. var index = observable.logSubscribedFrame();
  19023. subscriber.add(new Subscription(function () {
  19024. observable.logUnsubscribedFrame(index);
  19025. }));
  19026. observable.scheduleMessages(subscriber);
  19027. return subscriber;
  19028. });
  19029. this.messages = messages;
  19030. this.subscriptions = [];
  19031. this.scheduler = scheduler;
  19032. }
  19033. ColdObservable.prototype.scheduleMessages = function (subscriber) {
  19034. var messagesLength = this.messages.length;
  19035. for (var i = 0; i < messagesLength; i++) {
  19036. var message = this.messages[i];
  19037. subscriber.add(this.scheduler.schedule(function (_a) {
  19038. var message = _a.message, subscriber = _a.subscriber;
  19039. message.notification.observe(subscriber);
  19040. }, message.frame, { message: message, subscriber: subscriber }));
  19041. }
  19042. };
  19043. return ColdObservable;
  19044. }(Observable));
  19045. applyMixins(ColdObservable, [SubscriptionLoggable]);
  19046. /**
  19047. * We need this JSDoc comment for affecting ESDoc.
  19048. * @ignore
  19049. * @extends {Ignored}
  19050. */
  19051. var HotObservable = (function (_super) {
  19052. __extends(HotObservable, _super);
  19053. function HotObservable(messages, scheduler) {
  19054. _super.call(this);
  19055. this.messages = messages;
  19056. this.subscriptions = [];
  19057. this.scheduler = scheduler;
  19058. }
  19059. /** @deprecated internal use only */ HotObservable.prototype._subscribe = function (subscriber) {
  19060. var subject = this;
  19061. var index = subject.logSubscribedFrame();
  19062. subscriber.add(new Subscription(function () {
  19063. subject.logUnsubscribedFrame(index);
  19064. }));
  19065. return _super.prototype._subscribe.call(this, subscriber);
  19066. };
  19067. HotObservable.prototype.setup = function () {
  19068. var subject = this;
  19069. var messagesLength = subject.messages.length;
  19070. /* tslint:disable:no-var-keyword */
  19071. for (var i = 0; i < messagesLength; i++) {
  19072. (function () {
  19073. var message = subject.messages[i];
  19074. /* tslint:enable */
  19075. subject.scheduler.schedule(function () { message.notification.observe(subject); }, message.frame);
  19076. })();
  19077. }
  19078. };
  19079. return HotObservable;
  19080. }(Subject));
  19081. applyMixins(HotObservable, [SubscriptionLoggable]);
  19082. var VirtualTimeScheduler = (function (_super) {
  19083. __extends(VirtualTimeScheduler, _super);
  19084. function VirtualTimeScheduler(SchedulerAction, maxFrames) {
  19085. var _this = this;
  19086. if (SchedulerAction === void 0) { SchedulerAction = VirtualAction; }
  19087. if (maxFrames === void 0) { maxFrames = Number.POSITIVE_INFINITY; }
  19088. _super.call(this, SchedulerAction, function () { return _this.frame; });
  19089. this.maxFrames = maxFrames;
  19090. this.frame = 0;
  19091. this.index = -1;
  19092. }
  19093. /**
  19094. * Prompt the Scheduler to execute all of its queued actions, therefore
  19095. * clearing its queue.
  19096. * @return {void}
  19097. */
  19098. VirtualTimeScheduler.prototype.flush = function () {
  19099. var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
  19100. var error, action;
  19101. while ((action = actions.shift()) && (this.frame = action.delay) <= maxFrames) {
  19102. if (error = action.execute(action.state, action.delay)) {
  19103. break;
  19104. }
  19105. }
  19106. if (error) {
  19107. while (action = actions.shift()) {
  19108. action.unsubscribe();
  19109. }
  19110. throw error;
  19111. }
  19112. };
  19113. VirtualTimeScheduler.frameTimeFactor = 10;
  19114. return VirtualTimeScheduler;
  19115. }(AsyncScheduler));
  19116. /**
  19117. * We need this JSDoc comment for affecting ESDoc.
  19118. * @ignore
  19119. * @extends {Ignored}
  19120. */
  19121. var VirtualAction = (function (_super) {
  19122. __extends(VirtualAction, _super);
  19123. function VirtualAction(scheduler, work, index) {
  19124. if (index === void 0) { index = scheduler.index += 1; }
  19125. _super.call(this, scheduler, work);
  19126. this.scheduler = scheduler;
  19127. this.work = work;
  19128. this.index = index;
  19129. this.active = true;
  19130. this.index = scheduler.index = index;
  19131. }
  19132. VirtualAction.prototype.schedule = function (state, delay) {
  19133. if (delay === void 0) { delay = 0; }
  19134. if (!this.id) {
  19135. return _super.prototype.schedule.call(this, state, delay);
  19136. }
  19137. this.active = false;
  19138. // If an action is rescheduled, we save allocations by mutating its state,
  19139. // pushing it to the end of the scheduler queue, and recycling the action.
  19140. // But since the VirtualTimeScheduler is used for testing, VirtualActions
  19141. // must be immutable so they can be inspected later.
  19142. var action = new VirtualAction(this.scheduler, this.work);
  19143. this.add(action);
  19144. return action.schedule(state, delay);
  19145. };
  19146. VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
  19147. if (delay === void 0) { delay = 0; }
  19148. this.delay = scheduler.frame + delay;
  19149. var actions = scheduler.actions;
  19150. actions.push(this);
  19151. actions.sort(VirtualAction.sortActions);
  19152. return true;
  19153. };
  19154. VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
  19155. if (delay === void 0) { delay = 0; }
  19156. return undefined;
  19157. };
  19158. VirtualAction.prototype._execute = function (state, delay) {
  19159. if (this.active === true) {
  19160. return _super.prototype._execute.call(this, state, delay);
  19161. }
  19162. };
  19163. VirtualAction.sortActions = function (a, b) {
  19164. if (a.delay === b.delay) {
  19165. if (a.index === b.index) {
  19166. return 0;
  19167. }
  19168. else if (a.index > b.index) {
  19169. return 1;
  19170. }
  19171. else {
  19172. return -1;
  19173. }
  19174. }
  19175. else if (a.delay > b.delay) {
  19176. return 1;
  19177. }
  19178. else {
  19179. return -1;
  19180. }
  19181. };
  19182. return VirtualAction;
  19183. }(AsyncAction));
  19184. var defaultMaxFrame = 750;
  19185. var TestScheduler = (function (_super) {
  19186. __extends(TestScheduler, _super);
  19187. function TestScheduler(assertDeepEqual) {
  19188. _super.call(this, VirtualAction, defaultMaxFrame);
  19189. this.assertDeepEqual = assertDeepEqual;
  19190. this.hotObservables = [];
  19191. this.coldObservables = [];
  19192. this.flushTests = [];
  19193. }
  19194. TestScheduler.prototype.createTime = function (marbles) {
  19195. var indexOf = marbles.indexOf('|');
  19196. if (indexOf === -1) {
  19197. throw new Error('marble diagram for time should have a completion marker "|"');
  19198. }
  19199. return indexOf * TestScheduler.frameTimeFactor;
  19200. };
  19201. TestScheduler.prototype.createColdObservable = function (marbles, values, error) {
  19202. if (marbles.indexOf('^') !== -1) {
  19203. throw new Error('cold observable cannot have subscription offset "^"');
  19204. }
  19205. if (marbles.indexOf('!') !== -1) {
  19206. throw new Error('cold observable cannot have unsubscription marker "!"');
  19207. }
  19208. var messages = TestScheduler.parseMarbles(marbles, values, error);
  19209. var cold = new ColdObservable(messages, this);
  19210. this.coldObservables.push(cold);
  19211. return cold;
  19212. };
  19213. TestScheduler.prototype.createHotObservable = function (marbles, values, error) {
  19214. if (marbles.indexOf('!') !== -1) {
  19215. throw new Error('hot observable cannot have unsubscription marker "!"');
  19216. }
  19217. var messages = TestScheduler.parseMarbles(marbles, values, error);
  19218. var subject = new HotObservable(messages, this);
  19219. this.hotObservables.push(subject);
  19220. return subject;
  19221. };
  19222. TestScheduler.prototype.materializeInnerObservable = function (observable, outerFrame) {
  19223. var _this = this;
  19224. var messages = [];
  19225. observable.subscribe(function (value) {
  19226. messages.push({ frame: _this.frame - outerFrame, notification: Notification.createNext(value) });
  19227. }, function (err) {
  19228. messages.push({ frame: _this.frame - outerFrame, notification: Notification.createError(err) });
  19229. }, function () {
  19230. messages.push({ frame: _this.frame - outerFrame, notification: Notification.createComplete() });
  19231. });
  19232. return messages;
  19233. };
  19234. TestScheduler.prototype.expectObservable = function (observable, unsubscriptionMarbles) {
  19235. var _this = this;
  19236. if (unsubscriptionMarbles === void 0) { unsubscriptionMarbles = null; }
  19237. var actual = [];
  19238. var flushTest = { actual: actual, ready: false };
  19239. var unsubscriptionFrame = TestScheduler
  19240. .parseMarblesAsSubscriptions(unsubscriptionMarbles).unsubscribedFrame;
  19241. var subscription;
  19242. this.schedule(function () {
  19243. subscription = observable.subscribe(function (x) {
  19244. var value = x;
  19245. // Support Observable-of-Observables
  19246. if (x instanceof Observable) {
  19247. value = _this.materializeInnerObservable(value, _this.frame);
  19248. }
  19249. actual.push({ frame: _this.frame, notification: Notification.createNext(value) });
  19250. }, function (err) {
  19251. actual.push({ frame: _this.frame, notification: Notification.createError(err) });
  19252. }, function () {
  19253. actual.push({ frame: _this.frame, notification: Notification.createComplete() });
  19254. });
  19255. }, 0);
  19256. if (unsubscriptionFrame !== Number.POSITIVE_INFINITY) {
  19257. this.schedule(function () { return subscription.unsubscribe(); }, unsubscriptionFrame);
  19258. }
  19259. this.flushTests.push(flushTest);
  19260. return {
  19261. toBe: function (marbles, values, errorValue) {
  19262. flushTest.ready = true;
  19263. flushTest.expected = TestScheduler.parseMarbles(marbles, values, errorValue, true);
  19264. }
  19265. };
  19266. };
  19267. TestScheduler.prototype.expectSubscriptions = function (actualSubscriptionLogs) {
  19268. var flushTest = { actual: actualSubscriptionLogs, ready: false };
  19269. this.flushTests.push(flushTest);
  19270. return {
  19271. toBe: function (marbles) {
  19272. var marblesArray = (typeof marbles === 'string') ? [marbles] : marbles;
  19273. flushTest.ready = true;
  19274. flushTest.expected = marblesArray.map(function (marbles) {
  19275. return TestScheduler.parseMarblesAsSubscriptions(marbles);
  19276. });
  19277. }
  19278. };
  19279. };
  19280. TestScheduler.prototype.flush = function () {
  19281. var hotObservables = this.hotObservables;
  19282. while (hotObservables.length > 0) {
  19283. hotObservables.shift().setup();
  19284. }
  19285. _super.prototype.flush.call(this);
  19286. var readyFlushTests = this.flushTests.filter(function (test) { return test.ready; });
  19287. while (readyFlushTests.length > 0) {
  19288. var test = readyFlushTests.shift();
  19289. this.assertDeepEqual(test.actual, test.expected);
  19290. }
  19291. };
  19292. TestScheduler.parseMarblesAsSubscriptions = function (marbles) {
  19293. if (typeof marbles !== 'string') {
  19294. return new SubscriptionLog(Number.POSITIVE_INFINITY);
  19295. }
  19296. var len = marbles.length;
  19297. var groupStart = -1;
  19298. var subscriptionFrame = Number.POSITIVE_INFINITY;
  19299. var unsubscriptionFrame = Number.POSITIVE_INFINITY;
  19300. for (var i = 0; i < len; i++) {
  19301. var frame = i * this.frameTimeFactor;
  19302. var c = marbles[i];
  19303. switch (c) {
  19304. case '-':
  19305. case ' ':
  19306. break;
  19307. case '(':
  19308. groupStart = frame;
  19309. break;
  19310. case ')':
  19311. groupStart = -1;
  19312. break;
  19313. case '^':
  19314. if (subscriptionFrame !== Number.POSITIVE_INFINITY) {
  19315. throw new Error('found a second subscription point \'^\' in a ' +
  19316. 'subscription marble diagram. There can only be one.');
  19317. }
  19318. subscriptionFrame = groupStart > -1 ? groupStart : frame;
  19319. break;
  19320. case '!':
  19321. if (unsubscriptionFrame !== Number.POSITIVE_INFINITY) {
  19322. throw new Error('found a second subscription point \'^\' in a ' +
  19323. 'subscription marble diagram. There can only be one.');
  19324. }
  19325. unsubscriptionFrame = groupStart > -1 ? groupStart : frame;
  19326. break;
  19327. default:
  19328. throw new Error('there can only be \'^\' and \'!\' markers in a ' +
  19329. 'subscription marble diagram. Found instead \'' + c + '\'.');
  19330. }
  19331. }
  19332. if (unsubscriptionFrame < 0) {
  19333. return new SubscriptionLog(subscriptionFrame);
  19334. }
  19335. else {
  19336. return new SubscriptionLog(subscriptionFrame, unsubscriptionFrame);
  19337. }
  19338. };
  19339. TestScheduler.parseMarbles = function (marbles, values, errorValue, materializeInnerObservables) {
  19340. if (materializeInnerObservables === void 0) { materializeInnerObservables = false; }
  19341. if (marbles.indexOf('!') !== -1) {
  19342. throw new Error('conventional marble diagrams cannot have the ' +
  19343. 'unsubscription marker "!"');
  19344. }
  19345. var len = marbles.length;
  19346. var testMessages = [];
  19347. var subIndex = marbles.indexOf('^');
  19348. var frameOffset = subIndex === -1 ? 0 : (subIndex * -this.frameTimeFactor);
  19349. var getValue = typeof values !== 'object' ?
  19350. function (x) { return x; } :
  19351. function (x) {
  19352. // Support Observable-of-Observables
  19353. if (materializeInnerObservables && values[x] instanceof ColdObservable) {
  19354. return values[x].messages;
  19355. }
  19356. return values[x];
  19357. };
  19358. var groupStart = -1;
  19359. for (var i = 0; i < len; i++) {
  19360. var frame = i * this.frameTimeFactor + frameOffset;
  19361. var notification = void 0;
  19362. var c = marbles[i];
  19363. switch (c) {
  19364. case '-':
  19365. case ' ':
  19366. break;
  19367. case '(':
  19368. groupStart = frame;
  19369. break;
  19370. case ')':
  19371. groupStart = -1;
  19372. break;
  19373. case '|':
  19374. notification = Notification.createComplete();
  19375. break;
  19376. case '^':
  19377. break;
  19378. case '#':
  19379. notification = Notification.createError(errorValue || 'error');
  19380. break;
  19381. default:
  19382. notification = Notification.createNext(getValue(c));
  19383. break;
  19384. }
  19385. if (notification) {
  19386. testMessages.push({ frame: groupStart > -1 ? groupStart : frame, notification: notification });
  19387. }
  19388. }
  19389. return testMessages;
  19390. };
  19391. return TestScheduler;
  19392. }(VirtualTimeScheduler));
  19393. var RequestAnimationFrameDefinition = (function () {
  19394. function RequestAnimationFrameDefinition(root$$1) {
  19395. if (root$$1.requestAnimationFrame) {
  19396. this.cancelAnimationFrame = root$$1.cancelAnimationFrame.bind(root$$1);
  19397. this.requestAnimationFrame = root$$1.requestAnimationFrame.bind(root$$1);
  19398. }
  19399. else if (root$$1.mozRequestAnimationFrame) {
  19400. this.cancelAnimationFrame = root$$1.mozCancelAnimationFrame.bind(root$$1);
  19401. this.requestAnimationFrame = root$$1.mozRequestAnimationFrame.bind(root$$1);
  19402. }
  19403. else if (root$$1.webkitRequestAnimationFrame) {
  19404. this.cancelAnimationFrame = root$$1.webkitCancelAnimationFrame.bind(root$$1);
  19405. this.requestAnimationFrame = root$$1.webkitRequestAnimationFrame.bind(root$$1);
  19406. }
  19407. else if (root$$1.msRequestAnimationFrame) {
  19408. this.cancelAnimationFrame = root$$1.msCancelAnimationFrame.bind(root$$1);
  19409. this.requestAnimationFrame = root$$1.msRequestAnimationFrame.bind(root$$1);
  19410. }
  19411. else if (root$$1.oRequestAnimationFrame) {
  19412. this.cancelAnimationFrame = root$$1.oCancelAnimationFrame.bind(root$$1);
  19413. this.requestAnimationFrame = root$$1.oRequestAnimationFrame.bind(root$$1);
  19414. }
  19415. else {
  19416. this.cancelAnimationFrame = root$$1.clearTimeout.bind(root$$1);
  19417. this.requestAnimationFrame = function (cb) { return root$$1.setTimeout(cb, 1000 / 60); };
  19418. }
  19419. }
  19420. return RequestAnimationFrameDefinition;
  19421. }());
  19422. var AnimationFrame = new RequestAnimationFrameDefinition(_root);
  19423. /**
  19424. * We need this JSDoc comment for affecting ESDoc.
  19425. * @ignore
  19426. * @extends {Ignored}
  19427. */
  19428. var AnimationFrameAction = (function (_super) {
  19429. __extends(AnimationFrameAction, _super);
  19430. function AnimationFrameAction(scheduler, work) {
  19431. _super.call(this, scheduler, work);
  19432. this.scheduler = scheduler;
  19433. this.work = work;
  19434. }
  19435. AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
  19436. if (delay === void 0) { delay = 0; }
  19437. // If delay is greater than 0, request as an async action.
  19438. if (delay !== null && delay > 0) {
  19439. return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
  19440. }
  19441. // Push the action to the end of the scheduler queue.
  19442. scheduler.actions.push(this);
  19443. // If an animation frame has already been requested, don't request another
  19444. // one. If an animation frame hasn't been requested yet, request one. Return
  19445. // the current animation frame request id.
  19446. return scheduler.scheduled || (scheduler.scheduled = AnimationFrame.requestAnimationFrame(scheduler.flush.bind(scheduler, null)));
  19447. };
  19448. AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
  19449. if (delay === void 0) { delay = 0; }
  19450. // If delay exists and is greater than 0, or if the delay is null (the
  19451. // action wasn't rescheduled) but was originally scheduled as an async
  19452. // action, then recycle as an async action.
  19453. if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
  19454. return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
  19455. }
  19456. // If the scheduler queue is empty, cancel the requested animation frame and
  19457. // set the scheduled flag to undefined so the next AnimationFrameAction will
  19458. // request its own.
  19459. if (scheduler.actions.length === 0) {
  19460. AnimationFrame.cancelAnimationFrame(id);
  19461. scheduler.scheduled = undefined;
  19462. }
  19463. // Return undefined so the action knows to request a new async id if it's rescheduled.
  19464. return undefined;
  19465. };
  19466. return AnimationFrameAction;
  19467. }(AsyncAction));
  19468. var AnimationFrameScheduler = (function (_super) {
  19469. __extends(AnimationFrameScheduler, _super);
  19470. function AnimationFrameScheduler() {
  19471. _super.apply(this, arguments);
  19472. }
  19473. AnimationFrameScheduler.prototype.flush = function (action) {
  19474. this.active = true;
  19475. this.scheduled = undefined;
  19476. var actions = this.actions;
  19477. var error;
  19478. var index = -1;
  19479. var count = actions.length;
  19480. action = action || actions.shift();
  19481. do {
  19482. if (error = action.execute(action.state, action.delay)) {
  19483. break;
  19484. }
  19485. } while (++index < count && (action = actions.shift()));
  19486. this.active = false;
  19487. if (error) {
  19488. while (++index < count && (action = actions.shift())) {
  19489. action.unsubscribe();
  19490. }
  19491. throw error;
  19492. }
  19493. };
  19494. return AnimationFrameScheduler;
  19495. }(AsyncScheduler));
  19496. /**
  19497. *
  19498. * Animation Frame Scheduler
  19499. *
  19500. * <span class="informal">Perform task when `window.requestAnimationFrame` would fire</span>
  19501. *
  19502. * When `animationFrame` scheduler is used with delay, it will fall back to {@link async} scheduler
  19503. * behaviour.
  19504. *
  19505. * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.
  19506. * It makes sure scheduled task will happen just before next browser content repaint,
  19507. * thus performing animations as efficiently as possible.
  19508. *
  19509. * @example <caption>Schedule div height animation</caption>
  19510. * const div = document.querySelector('.some-div');
  19511. *
  19512. * Rx.Scheduler.schedule(function(height) {
  19513. * div.style.height = height + "px";
  19514. *
  19515. * this.schedule(height + 1); // `this` references currently executing Action,
  19516. * // which we reschedule with new state
  19517. * }, 0, 0);
  19518. *
  19519. * // You will see .some-div element growing in height
  19520. *
  19521. *
  19522. * @static true
  19523. * @name animationFrame
  19524. * @owner Scheduler
  19525. */
  19526. var animationFrame = new AnimationFrameScheduler(AnimationFrameAction);
  19527. var _operators = Object.freeze({
  19528. audit: audit$1,
  19529. auditTime: auditTime$1,
  19530. buffer: buffer$1,
  19531. bufferCount: bufferCount$1,
  19532. bufferTime: bufferTime$1,
  19533. bufferToggle: bufferToggle$1,
  19534. bufferWhen: bufferWhen$1,
  19535. catchError: catchError,
  19536. combineAll: combineAll$1,
  19537. combineLatest: combineLatest$1,
  19538. concat: concat$2,
  19539. concatAll: concatAll,
  19540. concatMap: concatMap$1,
  19541. concatMapTo: concatMapTo$1,
  19542. count: count$1,
  19543. debounce: debounce$1,
  19544. debounceTime: debounceTime$1,
  19545. defaultIfEmpty: defaultIfEmpty$1,
  19546. delay: delay$1,
  19547. delayWhen: delayWhen$1,
  19548. dematerialize: dematerialize$1,
  19549. distinct: distinct$1,
  19550. distinctUntilChanged: distinctUntilChanged$1,
  19551. distinctUntilKeyChanged: distinctUntilKeyChanged$1,
  19552. elementAt: elementAt$1,
  19553. every: every$1,
  19554. exhaust: exhaust$1,
  19555. exhaustMap: exhaustMap$1,
  19556. expand: expand$1,
  19557. filter: filter$1,
  19558. finalize: finalize,
  19559. find: find$1,
  19560. findIndex: findIndex$1,
  19561. first: first$1,
  19562. groupBy: groupBy$1,
  19563. ignoreElements: ignoreElements$1,
  19564. isEmpty: isEmpty$1,
  19565. last: last$1,
  19566. map: map,
  19567. mapTo: mapTo$1,
  19568. materialize: materialize$1,
  19569. max: max$1,
  19570. merge: merge$2,
  19571. mergeAll: mergeAll,
  19572. mergeMap: mergeMap,
  19573. flatMap: mergeMap,
  19574. mergeMapTo: mergeMapTo$1,
  19575. mergeScan: mergeScan$1,
  19576. min: min$1,
  19577. multicast: multicast$1,
  19578. observeOn: observeOn,
  19579. onErrorResumeNext: onErrorResumeNext$1,
  19580. pairwise: pairwise$1,
  19581. partition: partition$1,
  19582. pluck: pluck$1,
  19583. publish: publish$1,
  19584. publishBehavior: publishBehavior$1,
  19585. publishLast: publishLast$1,
  19586. publishReplay: publishReplay$1,
  19587. race: race$2,
  19588. reduce: reduce,
  19589. repeat: repeat$1,
  19590. repeatWhen: repeatWhen$1,
  19591. retry: retry$1,
  19592. retryWhen: retryWhen$1,
  19593. refCount: refCount,
  19594. sample: sample$1,
  19595. sampleTime: sampleTime$1,
  19596. scan: scan,
  19597. sequenceEqual: sequenceEqual$1,
  19598. share: share$1,
  19599. shareReplay: shareReplay$1,
  19600. single: single$1,
  19601. skip: skip$1,
  19602. skipLast: skipLast$1,
  19603. skipUntil: skipUntil$1,
  19604. skipWhile: skipWhile$1,
  19605. startWith: startWith$1,
  19606. switchAll: switchAll,
  19607. switchMap: switchMap,
  19608. switchMapTo: switchMapTo$1,
  19609. take: take$1,
  19610. takeLast: takeLast,
  19611. takeUntil: takeUntil$1,
  19612. takeWhile: takeWhile$1,
  19613. tap: tap,
  19614. throttle: throttle$1,
  19615. throttleTime: throttleTime$1,
  19616. timeInterval: timeInterval$1,
  19617. timeout: timeout$1,
  19618. timeoutWith: timeoutWith$1,
  19619. timestamp: timestamp$1,
  19620. toArray: toArray$1,
  19621. window: window$2,
  19622. windowCount: windowCount$1,
  19623. windowTime: windowTime$1,
  19624. windowToggle: windowToggle$1,
  19625. windowWhen: windowWhen$1,
  19626. withLatestFrom: withLatestFrom$1,
  19627. zip: zip$1,
  19628. zipAll: zipAll$1
  19629. });
  19630. /* tslint:disable:no-unused-variable */
  19631. // Subject imported before Observable to bypass circular dependency issue since
  19632. // Subject extends Observable and Observable references Subject in it's
  19633. // definition
  19634. var operators = _operators;
  19635. /* tslint:enable:no-unused-variable */
  19636. /**
  19637. * @typedef {Object} Rx.Scheduler
  19638. * @property {Scheduler} queue Schedules on a queue in the current event frame
  19639. * (trampoline scheduler). Use this for iteration operations.
  19640. * @property {Scheduler} asap Schedules on the micro task queue, which uses the
  19641. * fastest transport mechanism available, either Node.js' `process.nextTick()`
  19642. * or Web Worker MessageChannel or setTimeout or others. Use this for
  19643. * asynchronous conversions.
  19644. * @property {Scheduler} async Schedules work with `setInterval`. Use this for
  19645. * time-based operations.
  19646. * @property {Scheduler} animationFrame Schedules work with `requestAnimationFrame`.
  19647. * Use this for synchronizing with the platform's painting
  19648. */
  19649. var Scheduler = {
  19650. asap: asap,
  19651. queue: queue,
  19652. animationFrame: animationFrame,
  19653. async: async
  19654. };
  19655. /**
  19656. * @typedef {Object} Rx.Symbol
  19657. * @property {Symbol|string} rxSubscriber A symbol to use as a property name to
  19658. * retrieve an "Rx safe" Observer from an object. "Rx safety" can be defined as
  19659. * an object that has all of the traits of an Rx Subscriber, including the
  19660. * ability to add and remove subscriptions to the subscription chain and
  19661. * guarantees involving event triggering (can't "next" after unsubscription,
  19662. * etc).
  19663. * @property {Symbol|string} observable A symbol to use as a property name to
  19664. * retrieve an Observable as defined by the [ECMAScript "Observable" spec](https://github.com/zenparsing/es-observable).
  19665. * @property {Symbol|string} iterator The ES6 symbol to use as a property name
  19666. * to retrieve an iterator from an object.
  19667. */
  19668. var Symbol$1 = {
  19669. rxSubscriber: rxSubscriber,
  19670. observable: observable,
  19671. iterator: iterator
  19672. };
  19673. exports.operators = operators;
  19674. exports.Scheduler = Scheduler;
  19675. exports.Symbol = Symbol$1;
  19676. exports.Subject = Subject;
  19677. exports.AnonymousSubject = AnonymousSubject;
  19678. exports.Observable = Observable;
  19679. exports.Subscription = Subscription;
  19680. exports.Subscriber = Subscriber;
  19681. exports.AsyncSubject = AsyncSubject;
  19682. exports.ReplaySubject = ReplaySubject;
  19683. exports.BehaviorSubject = BehaviorSubject;
  19684. exports.ConnectableObservable = ConnectableObservable;
  19685. exports.Notification = Notification;
  19686. exports.EmptyError = EmptyError;
  19687. exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
  19688. exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
  19689. exports.TimeoutError = TimeoutError;
  19690. exports.UnsubscriptionError = UnsubscriptionError;
  19691. exports.TimeInterval = TimeInterval;
  19692. exports.Timestamp = Timestamp;
  19693. exports.TestScheduler = TestScheduler;
  19694. exports.VirtualTimeScheduler = VirtualTimeScheduler;
  19695. exports.AjaxResponse = AjaxResponse;
  19696. exports.AjaxError = AjaxError;
  19697. exports.AjaxTimeoutError = AjaxTimeoutError;
  19698. exports.pipe = pipe;
  19699. Object.defineProperty(exports, '__esModule', { value: true });
  19700. })));