Skip to content

Fix Live Translation not working when app returns to foreground #95

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions MyLibrary/Sources/LiveTranslationFeature/LiveTranslationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ public struct LiveTranslationView: View {
@State var isSelectedLanguageSheet: Bool = false
@State var isShowingLastChat: Bool = false

@Environment(\.scenePhase) var scenePhase

private let scrollContentBottomID: String = "atBottom"

public init(
Expand Down Expand Up @@ -80,6 +82,16 @@ public struct LiveTranslationView: View {
viewModel.send(.onAppearedPage)
viewModel.send(.connectChatStream)
}
.onChange(of: scenePhase) {
switch scenePhase {
case .inactive: break
case .active:
viewModel.send(.connectChatStream)
case .background:
viewModel.send(.disconnectChatStream)
@unknown default: break
}
}
.navigationTitle(Text("Live translation", bundle: .module))
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Expand Down
8 changes: 7 additions & 1 deletion MyLibrary/Sources/LiveTranslationFeature/ViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public final class ViewModel {
var updateChatWaitingQueue: [RealTimeEntity.Chat.Response] = []
var updateTrWaitingQueue: [RealTimeEntity.Translation.Response] = []
var latestListType: RealTimeEntity.ListType? = .none
var chatStreamTask: Task<Void, Never>? = nil
}

extension ViewModel {
Expand All @@ -37,9 +38,13 @@ extension ViewModel {
}
}
case .connectChatStream:
Task {
chatStreamTask = Task {
await connectChatStream(roomNumber)
}

case .disconnectChatStream:
chatStreamTask?.cancel()

case .changeLangCode(let newLangCode):
selectedLangCode = newLangCode
Task {
Expand Down Expand Up @@ -315,6 +320,7 @@ extension ViewModel {
public enum InputAction {
case onAppearedPage
case connectChatStream
case disconnectChatStream
case changeLangCode(String)
}
}
Expand Down