function RxBrioUtils.emitWhileAllDead(p)return function(A)return Observable.new(function(l)local G=Maid.new()local c=true G:GiveTask(function()c=false end)local X={}local f=false local function o()if not c then return end X=BrioUtils.aliveOnly(X)if next(X)then G._lastBrio=nil else local A=Brio.new(p)G._lastBrio=A l:Fire(A)end f=true end local function m(p)if p:IsDead()then return end local A=Maid.new()G[A]=A A:GiveTask(function()G[A]=nil o()end)A:GiveTask((p:GetDiedSignal()):Connect(function()G[A]=nil end))table.insert(X,p)o()end G:GiveTask(A:Subscribe(function(p)if not Brio.isBrio(p)then warn(("\091\082\120\066\114\105\111\085\116\105\108\115\046\101\109\105\116\087\104\105\108\101\065\108\108\068\101\097\100\093 - \078\111\116 \097 \098\114\105\111\044 \037\113"):format(tostring(p)))G._lastBrio=nil l:Fail("\078\111\116 \097 \098\114\105\111")return end m(p)end,function(...)l:Fail(...)end,function(...)l:Complete(...)end))if not f then o()end return G end)end end
--[=[
	Whenever all returned brios are dead, emits this value wrapped
	in a brio.

	@param valueToEmitWhileAllDead T
	@return (source: Observable<Brio<U>>) -> Observable<Brio<U | T>>
]=]
function RxBrioUtils.emitWhileAllDead(valueToEmitWhileAllDead)
	return function(source)
		return Observable.new(function(sub)
			local topMaid = Maid.new()

			local subscribed = true
			topMaid:GiveTask(function()
				subscribed = false
			end)
			local aliveBrios = {}
			local fired = false

			local function updateBrios()
				if not subscribed then -- No work if we don't need to.
					return
				end

				aliveBrios = BrioUtils.aliveOnly(aliveBrios)
				if next(aliveBrios) then
					topMaid._lastBrio = nil
				else
					local newBrio = Brio.new(valueToEmitWhileAllDead)
					topMaid._lastBrio = newBrio
					sub:Fire(newBrio)
				end

				fired = true
			end

			local function handleNewBrio(brio)
				-- Could happen due to throttle or delay...
				if brio:IsDead() then
					return
				end

				local maid = Maid.new()
				topMaid[maid] = maid -- Use maid as key so it's unique (reemitted brio)

				maid:GiveTask(function() -- GC properly
					topMaid[maid] = nil
					updateBrios()
				end)
				maid:GiveTask(brio:GetDiedSignal():Connect(function()
					topMaid[maid] = nil
				end))

				table.insert(aliveBrios, brio)
				updateBrios()
			end

			topMaid:GiveTask(source:Subscribe(function(brio)
				if not Brio.isBrio(brio) then
					warn(("[RxBrioUtils.emitWhileAllDead] - Not a brio, %q"):format(tostring(brio)))
					topMaid._lastBrio = nil
					sub:Fail("Not a brio")
					return
				end

				handleNewBrio(brio)
			end, function(...)
				sub:Fail(...)
			end, function(...)
				sub:Complete(...)
			end))

			-- Make sure we emit an empty list if we discover nothing
			if not fired then
				updateBrios()
			end

			return topMaid
		end)
	end
end
