--[=[
	Transforms the brio into an observable that emits the initial value of the brio, and then another value on death
	@param brio Brio<T> | T
	@param emitOnDeathValue U
	@return Observable<T | U>
]=]

function RxBrioUtils.toEmitOnDeathObservable(brio, emitOnDeathValue)
	if not Brio.isBrio(brio) then
		return Rx.of(brio)
	else
		return Observable.new(function(sub)
			if brio:IsDead() then
				sub:Fire(emitOnDeathValue)
				sub:Complete()
			else
				sub:Fire(brio:GetValue())

				-- Firing killed the subscription
				if not sub:IsPending() then
					return
				end

				-- Firing this event actually killed the brio
				if brio:IsDead() then
					sub:Fire(emitOnDeathValue)
					sub:Complete()
				else
					return brio:GetDiedSignal():Connect(function()
						sub:Fire(emitOnDeathValue)
						sub:Complete()
					end)
				end
			end
		end)
	end
end
