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

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

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

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