--[=[
	Observes for the key
	@param key TKey
	@param retrieveInitialValue callback -- Optional
	@return Observable<TEmit>
]=]

function ObservableSubscriptionTable:Observe(key, retrieveInitialValue)
	assert(key ~= nil, "Bad key")

	return Observable.new(function(sub)
		if not self._subMap[key] then
			self._subMap[key] = { sub }
		else
			table.insert(self._subMap[key], sub)
		end

		if retrieveInitialValue then
			retrieveInitialValue(sub)
		end

		return function()
			if not self._subMap[key] then
				return
			end

			local current = self._subMap[key]
			local index = table.find(current, sub)
			if not index then
				return
			end

			table.remove(current, index)
			if #current == 0 then
				self._subMap[key] = nil
			end

			-- Complete the subscription
			if sub:IsPending() then
				task.spawn(function()
					sub:Complete()
				end)
			end
		end
	end)
end
