Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Help] How to implement KotlinSuspendFunction1 in Swift? #72

Closed
matt-ramotar opened this issue Aug 14, 2022 · 2 comments
Closed

[Help] How to implement KotlinSuspendFunction1 in Swift? #72

matt-ramotar opened this issue Aug 14, 2022 · 2 comments

Comments

@matt-ramotar
Copy link

Hey! Awesome library. QQ - How to implement KotlinSuspendFunction1 in Swift?

Kotlin function signature:

    fun <T: Cacheable> sync(
        key: String,
        getFromRemote: suspend (key: String) -> Result<T, Exception>,
        onCompletion: (Result<*, Exception>) -> Unit = {}
    )

Swift usage:

    init () {
        treeSquirrel.sync(key: KEY, getFromRemote: <#T##KotlinSuspendFunction1#> , onCompletion: { result in
            self.onCompletion(result: result)
        } )
    }

Swift callback I want to pass in treeSquirrel.sync():

func getFromRemote(){
        Task {
            do {
                let response = await asyncResult(for: api.fetchNative(url: URL))
                
                guard case let .success(result) = response else { return }

                let model = try? JSONDecoder().decode(
                    Model.self,
                    from: result.data(using: .utf8)!
                )
                
                self.result = Model(id: model.id)  
            } 
        }
    }
@rickclephas
Copy link
Owner

Hi! At the moment Swift to Kotlin cases aren't supported, see #42.
But the logic would be pretty similar. E.g. instead of the suspend lambda you would have to expose a lambda with a completion handler.

Something like the following should work (but doesn't support cancellation):

fun <T: Cacheable> sync(
    key: String,
    getFromRemote: (key: String, completionHandler: (Result<T, Exception>) -> Unit) -> Unit,
    onCompletion: (Result<*, Exception>) -> Unit = {}
)

@matt-ramotar
Copy link
Author

Got it - Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants