nmdias / FeedKit

An RSS, Atom and JSON Feed parser written in Swift
MIT License
1.19k stars 173 forks source link

Operation queue, cancel #5

Closed vaderdan closed 7 years ago

vaderdan commented 7 years ago

Hi, I've question.

How I can use this library with NSOperationQueue and is there any way to cancel FeedKit parse request. is the XMLParser's abortParsing method appropriate for that?

nmdias commented 7 years ago

Hi @vaderdan,

I've just exposed the XMLParser's abortParsing method in the FeedParser class here.

It will be available in the next release. For now you can checkout the master, in order to get it.

As for the operation queue, I guess it would be vey similar to the example provided here with Swift 3's dispatch queue.

I haven't tested this myself with OperationQueue, but it should go along the lines of:

let queue = OperationQueue()

queue.addOperation() {
    // Run parsing in the background
    FeedParser(URL: feedURL)!.parse { (result) in
        OperationQueue.main.addOperation() {
            // Perform updates in the main queue when finished
        }
    }
}
vaderdan commented 7 years ago

Thanks for letting me to try the abortParsing method!! 😄 I tested it a bit here:

I've tested the operation queue and it works. Here is some sample of the FeedKitOperation class

import Foundation
import FeedKit

public class FeedKitOperation: ConcurrentOperation {
    var parser:FeedParser?
    let url:URL
    let completionHandler: (Result) -> Void

    public init(url:URL, _ completion: @escaping (Result) -> Void) {
        self.url = url
        self.completionHandler = completion
        super.init()
    }

    override public func main() {
        self.parser = FeedParser(URL: url)
        self.parser?.parse({ result in
            var result = result
            self.state = .finished

            if self.isCancelled {
                result = .failure(NSError.init(domain: "Cancelled", code: -1, userInfo: nil))
            }

            self.completionHandler(result)
        })
    }

    override public func cancel() {
        super.cancel()
        parser?.abortParsing()
    }
}

I used this gist https://gist.github.com/calebd/93fa347397cec5f88233 as ConcurrentOperation class.

vaderdan commented 7 years ago

My tests are in this repository https://github.com/vaderdan/FeedKitTest

vaderdan commented 7 years ago

Can I close this issue?

nmdias commented 7 years ago

Cool, thanks for sharing :)