https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
o

Osman Saral

12/04/2023, 6:27 PM
I'm trying to use
KMP-NativeCoroutines
library and I'm getting
Escaping closure captures mutating 'self' parameter
error. The shared ViewModel has this:
Copy code
private val _incomingMessage = MutableSharedFlow<Incoming>(10)
@NativeCoroutines
val incomingMessage = _incomingMessage.asSharedFlow()
Any idea what's wrong?
r

Rick Clephas

12/04/2023, 6:34 PM
Could you share some more of the Swift code? Specifically regarding
self
and
mainViewModel
.
o

Osman Saral

12/04/2023, 6:37 PM
Sure:
Copy code
@main
struct MyApp: App {
    let mainViewModel: MainViewModel = inject()
    
    init() {
        print("Starting app")
        KoinApplication.start()
        
        let handle = Task {
            do {
                let sequence = asyncSequence(for: self.mainViewModel.incomingMessage)
                for try await message in sequence {
                    print("Message: \(message)")
                }
            } catch {
                print("Failed with error: \(error)")
            }
        }
    }
}



func inject<T : AnyObject>() -> T {
    return KoinApplication.shared.koin.get(objCClass: T.self) as! T
}


typealias KoinApplication = Koin_coreKoinApplication

extension KoinApplication {
    static let shared = KoinIOSKt.doInitKoinIos()

  @discardableResult
  static func start() -> KoinApplication {
    shared
  }
}
r

Rick Clephas

12/04/2023, 6:49 PM
Seems that is to be expected due to
init
being mutating. Adding
[self]
should fix it:
Copy code
let handle = Task { [self] in
source
o

Osman Saral

12/04/2023, 6:55 PM
Thank you @Rick Clephas. I knew how to fix it but still I didn't understand what's wrong. Which init is mutating?
r

Rick Clephas

12/04/2023, 7:00 PM
The
init
of the
MyApp
struct. Inside the init
self
is mutating which is captured by the Tasks escaping closure. Per the comment: that is and error by default, unless explicitly specifying the captured self (which makes self immutable).
🙏 1
o

Osman Saral

12/04/2023, 7:03 PM
Oh okay, all
init
s are mutating. Got it, thank you
👍 1
11 Views