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

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

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

def stream_response(client, customer_id, query):
    return client.get_service("GoogleAdsService", version="v16").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="v16")
    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.