   return (ClientContext chan cq cqt)
 
 destroyClientContext :: ClientContext -> IO ()
-destroyClientContext (ClientContext _ cq w) = do
-  completionQueueShutdown cq
-  CQ.waitWorkerTermination w
+destroyClientContext ClientContext{ccCQ, ccWorker} = do
+  completionQueueShutdown ccCQ
+  CQ.waitWorkerTermination ccWorker
 
 type MethodName = Slice
 type Arg = B.ByteString
 
--- | Run the IO function once, cache it in the MVar.
-onceMVar :: MVar (Maybe a) -> IO a -> IO a
-onceMVar mvar io = modifyMVar mvar $ \x ->
-  case x of
-    Just x' -> return (x, x')
-    Nothing -> do
-      x' <- io
-      return (Just x', x')
-
 reservedPtr :: Ptr ()
 reservedPtr = C.nullPtr
 
 data UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show
 
 callUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))
-callUnary ctx@(ClientContext chan cq _) co method arg = do
+callUnary ctx@ClientContext{ccChannel, ccCQ} co method arg = do
   deadline <- resolveDeadline co
-  bracket (grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline) grpcCallUnref $ \call0 -> newMVar call0 >>= \mcall -> do
+  bracket (grpcChannelCreateCall (cChannel ccChannel) C.nullPtr propagateDefaults ccCQ method (cHost ccChannel) deadline) grpcCallUnref $ \call0 -> newMVar call0 >>= \mcall -> do
     crw <- newClientReaderWriter ctx mcall
 
     sendInitOp <- opSendInitialMetadata (metadataToSend co)

-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
--------------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}
module Network.Grpc.Core.Call where


import           Control.Concurrent

        RpcError err -> return (RpcError err)

callBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))
callBidi ctx@ClientContext{ccChannel, ccCQ} co method = do
  deadline <- resolveDeadline co
  mcall <- grpcChannelCreateCall (cChannel ccChannel) C.nullPtr propagateDefaults ccCQ method (cHost ccChannel) deadline >>= newMVar

  crw <- newClientReaderWriter ctx mcall
  let client = Client crw defaultEncoder defaultDecoder
