--[=[
	Ensures only the last brio survives.

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

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

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

				local wrapperBrio = BrioUtils.clone(brio)
				maid._lastBrio = wrapperBrio

				sub:Fire(wrapperBrio)
			end, sub:GetFailComplete()))

			return maid
		end)
	end
end
