ReactiveCocoa-如何避免多次订阅collectionView单元格中的信号

时间:2016-07-23 13:22:33

标签: swift reactive-cocoa reactive-cocoa-4

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ComposeCell
    cell.deletePictureSignal.subscribeNext { (response) -> Void in
        print("delete picture")
        let deleteIndex = (self.pictureView.indexPathForCell(cell)?.item)!
        self.pictures.removeAtIndex(deleteIndex)
        //            self.pictureView.reloadData()
    }
    cell.addPictureSignal.subscribeNext { (response) -> Void in
        print("add picture")
        self.selectedIndex = (self.pictureView.indexPathForCell(cell)?.item)!
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        self.presentViewController(imagePicker, animated: true, completion: nil)
    }
   return cell
}

当我重新加载数据时,这种方式将再次实现,并且Signal将多次订阅,我该如何解决它并确保只订阅一次?

1 个答案:

答案 0 :(得分:0)

最后,我自己解决了...... 我使用“takeUntil”的方式,就像这样

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ComposeCell



    cell.deletePictureSigin.takeUntil(cell.rac_prepareForReuseSignal).subscribeNext { (response) -> Void in
        print("delete Picture")
        let deleteIndex:Int = (self.pictureView.indexPathForCell(cell)?.item)!
        self.pictures.removeAtIndex(deleteIndex)
        self.pictureView.reloadData()
    }

    cell.addPictureSigin.takeUntil(cell.rac_prepareForReuseSignal).subscribeNext { (response) -> Void in
        print("add Picture")
        self.selectedIndex = (self.pictureView.indexPathForCell(cell)?.item)!
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        self.presentViewController(imagePicker, animated: true, completion: nil)
    }


    if indexPath.item == pictures.count {
        cell.image = nil
    } else {
        cell.image = pictures[indexPath.item]
    }
    return cell
}