Upgrade to Pro — share decks privately, control downloads, hide ads and more …

iOS アプリ開発におけるデータストリーム超入門

iOS アプリ開発におけるデータストリーム超入門

Mitsuharu Emoto

December 13, 2023
Tweet

More Decks by Mitsuharu Emoto

Other Decks in Programming

Transcript

  1. σʔλετϦʔϜͷ࣮૷ w σʔλͷൃߦʢ1VCMJTIFSʣɺߪಡʢ4VCTDSJCFSʣΛ੍ޚ͢Δ w ͓ͦΒ͘࠷΋؆୯ͳͷ͸/PUJ fi DBUJPO$FOUFSΛར༻͢Δ w QPTU @

    BEE0CTFSWFS GPS/BNFPCKFDURVFVFVTJOH  w ࠓճ͸$PNCJOFΛར༻͠·ͨ͠ w /PUJ fi DBUJPO$FOUFSͱ૊Έ߹ΘͤΔํ๏΋͋Γ·͕͢ɺࠓճ͸୯ମར༻ 5
  2. $PNCJOFΛ࢖ͬͨ஋ड৴ w ൃߦ͞Εͨ஋ΛTJOL Ͱड͚औΔ w ஋ΛίʔϧόοΫʢΫϩʔδϟʣͰ͸ͳͯ͘BXBJUͰड͚औΓ͍ͨͳʜ var subscriptions = [AnyCancellable]()

    func receive(completion: (String) -> Void) -> Future <String, Never> { guard let self else { return } self.subject.sink { [weak self] in // ׬ྃ΍Τϥʔॲཧ } receiveValue: { completion($0) }.store(in: &self.subscriptions) } 7
  3. $PNCJOFΛ࢖ͬͨ஋ड৴ʢվʣ w J04Ҏ্ͷ৔߹ɺ'VUVSFͰ 4XJGU$PODVSSFODZʹม׵Ͱ͖Δ w J04ະຬ͸ɺίʔϧόοΫΛ XJUI$IFDLFE$POUJOVBUBJPOͳ ͲͰม׵͢Δ w 04WFSࠩ΍ม׵͕͋Δͱγϯϓϧ

    ͡Όͳ͍͠ɺίʔυྔ΋૿͑Δʜ var subscriptions = [AnyCancellable]() func receive() -> Future <String, Never> { return Future { [weak self] promise in guard let self else { return } self.subject.sink { [weak self] in // ׬ྃ΍Τϥʔॲཧ } receiveValue: { promise(.success($0)) }.store(in: &self.subscriptions) } } func take() async -> Void { let value = await receive().value // … } 8
  4. "TZOD4USFBN w "TZOD4USFBNΛܧঝͨ͠ϓϩύ ςΟʢTUSFBNʣΛ࡞Δ w ௨ৗͷίʔυͱετϦʔϜͷΠ ϯλϑΣʔεͷDPOUJOVBUJPO ΛൃՐͤ͞Δ w ൃߦͷQVU࣌ʹZJFME

    Λ࣮ߦ w தؒͷIBOEMFS΋͋ͬͯෳࡶʜ var handler: ((String) -> Void)? var stream: AsyncStream<String> { AsyncStream { [weak self] continuation in self?.handler = { value in continuation.yield(value) } } } func put(_ value: String){ handler?(value) } for await value in stream { print("streamed value is \(value)") } 10
  5. γϯϓϧͳ"TZOD4USFBN w J04%FQMPZNFOU5BSHFUҎ্ʹ͢Δͱɺ.JOJNVN%FQMPZNFOUT ͕J04Ҏ্ͷ؀ڥʹόοΫσϓϩΠ͞ΕΔ let (stream, continuation) = AsyncStream.makeStream(of: String.self)

    func put(_ value: String){ continuation.yield(value) } for await value in stream { print("streamed value is \(value)") } 11 IUUQTEFWFMPQFSBQQMFDPNEPDVNFOUBUJPOTXJGUBTZODTUSFBNNBLFTUSFBN PGCV ff FSJOHQPMJDZ