a zip code crypto-currency system good for red ONLY

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263
  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.work = work;
  4519. this.pending = false;
  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 (encodeURI(key) + "=" + encodeURI(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. })));