--[=[
	Whenever the last brio dies, reemit it as a dead brio

	@return (source Observable<Brio<T>>) -> Observable<Brio<T>>
]=]

function RxBrioUtils.reemitLastBrioOnDeath()
	return function(source)
		return Observable.new(function(sub)
			local maid = Maid.new()

			maid:GiveTask(source:Subscribe(
				function(brio)
					maid._conn = nil

					if not Brio.isBrio(brio) then
						warn(("[RxBrioUtils.reemitLastBrioOnDeath] - Not a brio, %q"):format(tostring(brio)))
						sub:Fail("Not a brio")
						return
					end

					if brio:IsDead() then
						sub:Fire(brio)
						return
					end

					-- Setup conn!
					maid._conn = brio:GetDiedSignal():Connect(function()
						sub:Fire(brio)
					end)

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

			return maid
		end)
	end
end
