ตัวซ้ำการสตรีม

เมื่อโทรหา GoogleAdsService.search_stream ระบบจะแสดงผลตัววนซ้ำการตอบกลับแบบสตรีม ตัววนซ้ำนี้ควรอยู่ในขอบเขตเดียวกันกับไคลเอ็นต์ GoogleAdsService ขณะใช้งานเพื่อหลีกเลี่ยงสตรีมที่ขาดตอนหรือข้อผิดพลาดในการแบ่งส่วน เนื่องจากระบบจะรวบรวมออบเจ็กต์ Channel ของ gRPC เมื่อออบเจ็กต์ GoogleAdsService ที่เปิดอยู่นอกขอบเขต หากออบเจ็กต์ GoogleAdsService ไม่อยู่ในขอบเขตอีกต่อไปเมื่อเกิดการทำซ้ำในผลลัพธ์ของ search_stream ออบเจ็กต์ Channel อาจถูกทำลายไปแล้ว ซึ่งจะทำให้เกิดลักษณะการทำงานที่ไม่แน่นอนเมื่อตัววนซ้ำพยายามดึงค่าถัดไป

โค้ดต่อไปนี้แสดงการใช้ตัววนซ้ำแบบสตรีมมิงที่ไม่ถูกต้อง

def stream_response(client, customer_id, query):
    return client.get_service("GoogleAdsService", version="v21").search_stream(customer_id, query=query)

def main(client, customer_id):
    query = "SELECT campaign.name FROM campaign LIMIT 10"
    response = stream_response(client, customer_id, query=query)
    # Access the iterator in a different scope from where the service object was created.
    try:
        for batch in response:
            # Iterate through response, expect undefined behavior.

ในโค้ดด้านบน ออบเจ็กต์ GoogleAdsService จะสร้างขึ้นภายใน ขอบเขตที่ต่างจากตำแหน่งที่เข้าถึงตัววนซ้ำ ด้วยเหตุนี้ ออบเจ็กต์ Channel อาจถูกทำลายก่อนที่ตัววนซ้ำจะใช้การตอบสนองทั้งหมด

แต่ตัววนซ้ำสตรีมควรอยู่ในขอบเขตเดียวกันกับ GoogleAdsServiceไคลเอ็นต์ตราบใดที่ยังมีการใช้งาน

def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService", version="v21")
    query = "SELECT campaign.name FROM campaign LIMIT 10"
    response = ga_service.search_stream(customer_id=customer_id, query=query)
    # Access the iterator in the same scope as where the service object was created.
    try:
        for batch in response:
            # Successfully iterate through response.