--[=[
	Converts a promise to an observable.
	@param observable Observable<T>
	@param cancelToken CancelToken?
	@return Promise<T>
]=]

function Rx.toPromise(observable, cancelToken)
	local maid = Maid.new()

	local newCancelToken = CancelToken.new(function(cancel)
		maid:GiveTask(cancel)
		if cancelToken then
			if cancelToken:IsCancelled() then
				cancel()
			else
				maid:GiveTask(cancelToken.Cancelled:Connect(cancel))
			end
		end
	end)

	local promise = Promise.new(function(resolve, reject)
		if newCancelToken:IsCancelled() then
			reject()
			return
		end

		maid:GiveTask(newCancelToken.Cancelled:Connect(function()
			reject()
		end))

		maid:GiveTask(observable:Subscribe(resolve, reject, reject))
	end)

	promise:Finally(function()
		maid:DoCleaning()
	end)

	return promise
end
